【问题标题】:How can I update a whole collection in MongoDB and not document by document?如何更新 MongoDB 中的整个集合而不是逐个文档?
【发布时间】:2018-03-09 13:49:20
【问题描述】:

在使用 pandas 进行一些分析后,我正在尝试更新 MongoDB 中的集合,这是我的代码:

client=MongoClient()
db=client.database
cll=db.collection

cursor=cll.find()
df=pd.DataFrame(list(cursor))

df['new_field'] = df['existing_field_A'].apply(lambda x: personalized_function(x))

for index, row in df.iterrows():
    _id=row['_id']
    new_value=row['new_field']
    cll.update_one({'_id':_id}, {'$set':{'new_field':new_value}})

代码运行良好,但需要很长时间。我想知道是否有更好的方法来更新我的收藏。

【问题讨论】:

    标签: python mongodb pandas pymongo


    【解决方案1】:

    您可以使用unordered-bulk-write-operations 并在一个批次中更新所有文档。这将提高性能。

        bulk_update = cll.initialize_unordered_bulk_op()
        for index, row in df.iterrows():
           _id=row['_id']
           new_value=row['new_field']
           bulk_update.find({'_id':_id}).update_one({'$set'{'new_field':new_value}})
        bulk_update.execute()
    

    【讨论】:

    • 在 $set 关键字后使用冒号 (:)。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-10-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-07
    相关资源
    最近更新 更多