【问题标题】:Pymongo Inserted Ids When BulkWriteError occurs发生 BulkWriteError 时 Pymongo 插入的 Id
【发布时间】:2020-12-24 00:32:47
【问题描述】:

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

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

【问题讨论】:

标签: python mongodb pymongo unique-index


【解决方案1】:

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

【讨论】:

  • 似乎没有其他办法......我已经看到了你分享的这个线程,不想再返回并再次查询以查找新插入的 ID ....期待不同的东西,但看起来没有其他办法......所以只需接受这个答案来标记这个问题已关闭。
猜你喜欢
  • 2016-11-16
  • 1970-01-01
  • 2012-09-23
  • 2013-10-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-02-05
相关资源
最近更新 更多