如何使用 insert_many 安全地忽略重复的键错误 [英] How to Ignore Duplicate Key Errors Safely Using insert_many
问题描述
在 pymongo 中使用 insert_many 时,我需要忽略重复插入,其中重复基于索引.我在 stackoverflow 上看到过这个问题,但我还没有看到有用的答案.
I need to ignore duplicate inserts when using insert_many with pymongo, where the duplicates are based on the index. I've seen this question asked on stackoverflow, but I haven't seen a useful answer.
这是我的代码片段:
try:
results = mongo_connection[db][collection].insert_many(documents, ordered=False, bypass_document_validation=True)
except pymongo.errors.BulkWriteError as e:
logger.error(e)
我希望 insert_many 忽略重复项而不抛出异常(这会填满我的错误日志).或者,是否有我可以使用的单独异常处理程序,以便我可以忽略错误.我想念w=0"...
I would like the insert_many to ignore duplicates and not throw an exception (which fills up my error logs). Alternatively, is there a separate exception handler I could use, so that I can just ignore the errors. I miss "w=0"...
谢谢
推荐答案
正确的解决方案是使用 w=0 的 WriteConcern:
The correct solution is to use a WriteConcern with w=0:
import pymongo
from pymongo.write_concern import WriteConcern
mongodb_connection[db][collection].with_options(write_concern=WriteConcern(w=0)).insert_many(messages)
这篇关于如何使用 insert_many 安全地忽略重复的键错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!