解决E11000重复密钥错误集合:_id_dup key in pymongo

2024-04-19 08:54:03 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图使用批量写入指令插入大量文档(+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似乎是一个bug,因为我在很多情况下都使用了这种方法,但我没有使用如此大的文档

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

我希望能找到解决这个问题的方法


Tags: toin文档id列表versionbulkdocument
2条回答

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

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

bulk.append(document.copy())

然后使用该列表创建查询

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

如果代码段中的任何documents已经包含一个_id,则不会添加新的_id,并且正如您所观察到的,您可能会遇到重复错误

相关问题 更多 >