使用来自 DF 的值更新 MongoDB

Update MongoDB with value from DF

我有一个数据框示例如下:

   request            new_request
0  Whats the time     What's the time?
1  its late           it's late!

然后我有一个 mongodb 集合如下:

{
    '_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)

此处有更多详细信息:https://www.w3schools.com/python/python_mongodb_update.asp