1

Is there a way of telling MongoDB to skip (instead of crashing) if we want to insert a document which has the same _id as an existing one?

Say, I have this list and I want to persist it:

to_mongo = [
    {'_id': 'aaaaaa', 'content': 'hey'},
    {'_id': 'bbbbbb', 'content': 'you'},
    {'_id': 'aaaaaa', 'content': 'hey'}
]

mongo_collection.insert_many(to_mongo)

I'd like the last item to be simply ignored, instead of causing the whole request to crash.

Jivan
  • 21,522
  • 15
  • 80
  • 131

1 Answers1

3

Try using the ordered=False in the insert_many() method i.e.

to_mongo = [
    {'_id': 'aaaaaa', 'content': 'hey'},
    {'_id': 'bbbbbb', 'content': 'you'},
    {'_id': 'aaaaaa', 'content': 'hey'}
]
mongo_collection.insert_many(to_mongo, ordered=False)

This makes sure that all write operations are attempted, even if there are errors. From the docs:

ordered (optional): If True (the default) documents will be inserted on the server serially, in the order provided. If an error occurs all remaining inserts are aborted. If False, documents will be inserted on the server in arbitrary order, possibly in parallel, and all document inserts will be attempted.

chridam
  • 100,957
  • 23
  • 236
  • 235