Python 使用来自DF的值更新MongoDB
我有一个dataframe示例,如下所示:Python 使用来自DF的值更新MongoDB,python,pandas,mongodb,pymongo,Python,Pandas,Mongodb,Pymongo,我有一个dataframe示例,如下所示: request new_request 0 Whats the time What's the time? 1 its late it's late! { '_id': 'b5445', 'request': 'Whats the time', 'accepted': True, 'aId': '6954c4', 'createDate': '1610
request new_request
0 Whats the time What's the time?
1 its late it's late!
{
'_id': 'b5445',
'request': 'Whats the time',
'accepted': True,
'aId': '6954c4',
'createDate': '1610726929114'
}
{
'_id': '4534fg', ,
'request': 'its late',
'accepted': True,
'aId': 'a86dfsb',
'createDate': '1610964941537'
}
然后我有一个mongodb集合,如下所示:
request new_request
0 Whats the time What's the time?
1 its late it's late!
{
'_id': 'b5445',
'request': 'Whats the time',
'accepted': True,
'aId': '6954c4',
'createDate': '1610726929114'
}
{
'_id': '4534fg', ,
'request': 'its late',
'accepted': True,
'aId': 'a86dfsb',
'createDate': '1610964941537'
}
我想更新mongoDB集合,使其看起来像:
{
'_id': 'b5445',
'request': "What's the time?",
'accepted': True,
'aId': '6954c4',
'createDate': '1610726929114'
}
{
'_id': '4534fg',
'request': "it's late!",
'accepted': True,
'aId': 'a86dfsb',
'createDate': '1610964941537'
}
我是mongoDB的新手,所以完全被卡住了。如何做到这一点?以下是一个示例:
import pymongo
myclient = pymongo.MongoClient('mongodb://localhost:27017/')
mydb = myclient['mydatabase']
mycol = mydb['customers']
#pandas dataframe
df = pd.DataFrame(columns = ['request', 'new_request'],
data = {'request': ['Whats the time', '''its late'''],
'new_request': ['''What's the time?''', '''it's late!''']})
#Update MongoDB collection one by one
for i in range(len(df)):
myquery = { 'request': df.iloc[i]['request'] }
newvalues = { '$set': { 'request': df.iloc[i]['new_request'] } }
mycol.update_one(myquery, newvalues)
此处有更多详细信息:我刚刚格式化了数据以便于阅读,我注意到在
\u id
字段之后的第二个数据块中有一个额外的逗号,它应该在那里吗?在最后一个数据块中也有重复的字段。我没有删除它们,以防这是你问题的一部分不,不应该是那样的。我修正了!