PyMongo insert_many with overwrite

I’ve recently needed to insert lots of objects into the Mongo collection. The only problem was that some of the objects would have an ‘_id’ key pre-set and would conflict with existing objects in the database.

PyMongo inser_many operation doesn’t support it out of the box, so here is a work-around using bulk api:

    bulk = collection.initialize_unordered_bulk_op() # or ordered
    objects_to_insert = (prepare generator for objects that need to be saved)
    for one in objects_to_insert:
        bulk.find({"_id": one["_id"]}).upsert().replace_one(one)
except BulkWriteError as exc:
    # exc.details available for more information
    pass # do something here


  1. I get a BulkWriteError: batch op errors occurred message after trying this. Have you got a working example?

    Thanks a lot

Leave a Reply

Your email address will not be published.