解决E11000 duplicate key error collection: _id_ dup key in pymongo

solve E11000 duplicate key error collection: _id_ dup key in pymongo

我正在尝试使用 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 自动完成的,我不知道如何解决这个问题,也许使用 UpdateOne with upsert True with一个不可能的过滤器,希望最好。

对于此问题的任何解决方案或解决方法,我将不胜感激

如果您的代码段中的任何 documents 已经包含一个 _id,则不会添加新的,并且您 运行 有重复错误的风险如您所见。

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

为了解决这个问题,我在列表中附加了一份文件

bulk.append(document.copy())

然后使用该列表创建查询

感谢@Belly Buster 对问题的帮助