使用 DF 中的值更新 MongoDB

问题描述 投票:0回答:2

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

   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 的新手,所以完全陷入困境。我该怎么做?

python pandas mongodb pymongo
2个回答
1
投票

这是一个例子:

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


0
投票

#其他选项:

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!''']}) 

df.apply(lambda x: mycol.update_one({'request': x['request']},{'$set': {'request': x['new_request']}}), axis=1)
© www.soinside.com 2019 - 2024. All rights reserved.