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

时间:2017-09-27 23:16:57

标签: python mongodb pandas pymongo

我正在尝试使用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}})

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

1 个答案:

答案 0 :(得分:0)

您可以使用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()