4
votes

I am trying to update the document if it exists and insert if it does not exist in a collection. I am inserting pandas data frame records as documents to collection based on _id. The insert of new document is working fine, but the update of fields in the old document is not working.

bulk = pymongo.bulk.BulkOperationBuilder(pros_rides,ordered=False)
for doc in bookings_df:
    bulk.find({ "_id": doc["_id"] }).upsert().update({
        "$setOnInsert": doc
    })
response = bulk.execute()

What do I miss?

1
what do you mean by is not working?styvane
@Styvane While doing upsert, when new record comes it does insert but when old record comes the document is not getting updated.Deepak selva

1 Answers

5
votes

An upsert can either update or insert a document; the "$setOnInsert" operation is only executed when the document is inserted, not when it is updated. In order to update the document if it exists, you must provide some operations that will be executed when the document is updated.

Try something like this instead:

bulk = pros_rides.initialize_unordered_bulk_op()
for doc in books_df:
    bulk.find({'_id': doc['_id']}).upsert().replace_one(doc)

bulk.execute()