python - 解决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)
根据文档,该_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 和一个不可能的过滤器并希望最好。
我将不胜感激任何解决方案或解决此问题
解决方案
似乎当我添加文档的新字段并将其附加到列表中时,我创建了相同元素的类似实例,所以我有相同的查询len(list_elements)
时间,这就是我出现重复键错误的原因。
为了解决这个问题,我将文档的副本附加到列表中
bulk.append(document.copy())
然后使用该列表创建查询
我要感谢@Belly Buster 在这个问题上的帮助
推荐阅读
- javascript - JQuery 升序和降序排序(不是表格)
- ios - iOS 使用哪个 UUID 作为键来缓存 BLE 设备的特征表?
- java - 使用 iText7 在现有 PDF 的特定页面中添加表格
- google-cloud-platform - 我怎么知道 google rsync 是否正常工作
- android - 调试构建变体失败
- java - 从 Stax XMLStreamReader 读取以解组部分
- react-native - 图标不会加载到标签栏场景/堆栈中
- apollo - 如何控制 Apollo 查询缓存以提供缓存数据并检查服务器是否有更新
- javascript - Chart js中的工具提示总是黑色而不是对应数据集的颜色
- spring-data-jpa - 使用多个事务管理器没有可用的名为“transactionManager”的 bean