繁体   English   中英

如何在MongoDB中更新整个集合,而不是逐个文档更新?

[英]How can I update a whole collection in MongoDB and not document by document?

使用熊猫做一些分析后,我试图在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}})

该代码可以正常工作,但是要花很长时间。 我想知道是否有更好的方式来更新我的收藏。

您可以使用无序批量写入操作并在一个批次中更新所有文档。 这样可以提高性能。

    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()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM