简体   繁体   English

通过匹配_id更新MongoDB集合

[英]Update MongoDB collection by matching _id

I am trying to update mongodb collection from Python using condition on _id 我正在尝试使用_id上的条件从Python更新mongodb集合

Like if I found match of _id in python dataframe I need to update corresponding document in colllection Below script is working, but it takes time for exeution if there are too many document is there any efficient way to handle this. 就像我在python数据帧中找到_id的匹配项一样,我需要在集合中更新相应的文档。下面的脚本正在工作,但是如果文档太多,那么执行任何有效的方法都需要执行时间。 Please advice 请指教

for document in db.AMTicketData.find():
    for index, row in AMTicketData1.iterrows():
        if(row['_id']==a['_id']):
            db.AMTicketData.update_one({'_id': row['_id']},{'$set': {'Application_Name': row['Application_Name']}}, upsert=True)
            break

I have used below bulk operation codes, was able to update collection in bulk 我在下面使用了批量操作代码,能够批量更新集合

bulk = db.AMTicketData.initialize_unordered_bulk_op()
for index, row in AMTicketData1.iterrows():
    bulk.find({'_id':row['_id']}).update_one({'$set':{'Application_Name':row['Application_Name']}})

bulk.execute()

You could try using bulk write. 您可以尝试使用批量写入。 You just have to create an array with all updates and apply it once with collection.bulk_write(list_of_updates) 您只需要创建一个包含所有更新的数组,然后使用collection.bulk_write(list_of_updates)对其应用一次即可。

Something like: 就像是:

updates = []
for document in db.AMTicketData.find():
   for index, row in AMTicketData1.iterrows():
     if(row['_id']==a['_id']):
      updates.append(UpdateOne({'_id': row['_id']}, {'$set': {'Application_Name': row['Application_Name']}}, upsert=True)
      break

db.AMTicketData.bulk_write(updates)

https://docs.mongodb.com/manual/core/bulk-write-operations/ https://docs.mongodb.com/manual/core/bulk-write-operations/

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

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