【发布时间】:2020-09-16 00:24:21
【问题描述】:
我正在尝试使用 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)
根据文档,_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 和不可能的过滤器和希望是最好的。
我会很感激这个问题的任何解决方案或解决方法
【问题讨论】: