首页 > 解决方案 > 解决E11000重复密钥错误收集:pymongo中的_id_ dup key

问题描述

我正在尝试使用 bulk_write 指令插入大量文档(+1M)。为此,我创建了一个 InsertOne 函数列表。

python version = 3.7.4

pymongo version = 3.8.0

文档创建:

document = {
    'dictionary': ObjectId(dictionary_id),
    'price': price,
    'source': source,
    'promo': promo,
    'date': now_utc,
    'updatedAt': now_utc,
    'createdAt:': now_utc
  }

# add line to debug
if '_id' in document.keys():
    print(document)

return document

我通过从元素列表中添加一个新字段来创建完整的文档列表,并使用 InsertOne 创建查询

bulk = []
for element in list_elements:
    for document in documents:
        document['new_field'] = element
        # add line to debug
        if '_id' in document.keys():
           print(document)
        insert = InsertOne(document)
        bulk.append(insert)
return bulk

我使用bulk_write命令进行插入

collection.bulk_write(bulk, ordered=False)

我附上文档https://api.mongodb.com/python/current/api/pymongo/collection.html#pymongo.collection.Collection.bulk_write

根据文档,该_id字段是自动添加 的Parameter - document: The document to insert. If the document is missing an _id field one will be added.

不知何故,这似乎做错了,因为其中一些具有相同的价值。为 1M 文档中的 700k 接收此错误(当然有不同的 _id)对 'E11000 duplicate key error collection: database.collection index: _id_ dup key: { _id: ObjectId(\'5f5fccb4b6f2a4ede9f6df62\') }' 我来说似乎是 pymongo 的一个错误,因为我在很多情况下都使用了这种方法,但我没有使用这么大的文档

_id字段必须是唯一的,但是,由于这是由 pymongo 自动完成的,我不知道如何解决这个问题,也许使用带有 upsert True 的 UpdateOne 和一个不可能的过滤器并希望最好。

我将不胜感激任何解决方案或解决此问题

标签: pythonpymongo

解决方案


似乎当我添加文档的新字段并将其附加到列表中时,我创建了相同元素的类似实例,所以我有相同的查询len(list_elements)时间,这就是我出现重复键错误的原因。

为了解决这个问题,我将文档的副本附加到列表中

bulk.append(document.copy())

然后使用该列表创建查询

我要感谢@Belly Buster 在这个问题上的帮助


推荐阅读