当BulkWriteError发生时Pymongo插入的ID

问题描述

我知道我们可以通过简单地访问inserted_ids操作返回的pymongo.results.InsertManyResult获取insert_many个插入的文档

>>> o = db.collection.insert_many([{"hash": "abcde"},{"hash": "efgh"}],ordered=False)
>>> o.inserted_ids
   [ObjectId('5f5280fdca7d7735e9dcbb85'),ObjectId('5f5280fdca7d7735e9dcbb86')]

但是,让我们考虑一下,在上述集合中有一个unique index字段(比如"hash"),现在我再插入两条记录,其中一条具有 duplicate 唯一字段插入会导致预期的异常 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'}}]}

但是我的问题是,我们能否获取成功插入的文档的插入ID(即'nInserted'所示)?

解决方法

不,你不能。请参阅我对Pymongo get inserted id's even with duplicate key error的回答,这是类似的问题。