2

I am trying to update mongodb collection from Python using condition on _id

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. 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()
user3734568
  • 1,311
  • 2
  • 22
  • 36

1 Answers1

2

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)

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/

  • Thanks for your reply. I tried but I am getting error "NameError: name 'UpdateOne' is not defined", Not sure why I am getting this error – user3734568 Mar 21 '19 at 05:02
  • I able to use bulk updates, I have edited my question with that codes, Thanks for your help and sharing information about bulk operation. – user3734568 Mar 22 '19 at 07:30