当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'所示)?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)