I know that we can get inserted_ids of documents inserted by simply accessing pymongo.results.InsertManyResult returned by insert_many operation
>>> o = db.collection.insert_many([{"hash": "abcde"}, {"hash": "efgh"}], ordered=False)
>>> o.inserted_ids
[ObjectId('5f5280fdca7d7735e9dcbb85'), ObjectId('5f5280fdca7d7735e9dcbb86')]
But Let's consider we have a unique index
field (let's say "hash"
) on above collection and now I insert two more records with one having duplicate unique field that is already inserted which would lead to an expected Exception BulkWriteError
>>> try:
o = db.collection.insert_many([{"hash": "efgh"}, {"hash": "ijk"}], ordered=False)
except BulkWriteError as e:
print(e.details)
{'nInserted': 1,
'nMatched': 0,
'nModified': 0,
'nRemoved': 0,
'nUpserted': 0,
'upserted': [],
'writeConcernErrors': [],
'writeErrors': [{'code': 11000,
'errmsg': 'E11000 duplicate key error collection: '
'db.collection index: hash_1 dup key: { : "efgh" }',
'index': 0,
'op': {'_id': ObjectId('5f52814381c45515348fd36b'),
'hash': 'efgh'}}]}
But my question is can we get inserted ids of documents that were successfully inserted (i.e shown by 'nInserted'
) ?