【问题标题】:MongoDB Bulk Silent UpdateMongoDB 批量静默更新
【发布时间】:2013-06-18 07:26:01
【问题描述】:

我需要在远程 MongoDB 实例中插入一组文档,其中一些文档可能已经驻留在实例中,即具有 _id 参数。我希望 MongoDB 忽略此类文档并提交其余文档。

目前 PyMongo 的 insert 方法的默认行为是,它为远程服务器上遇到的每个重复文档返回一个 DuplicateError 异常。我想把这种行为压制得更火,忘记那种功能。

如果有人知道如何做到这一点。这将是可观的。

【问题讨论】:

标签: mongodb bulkinsert


【解决方案1】:

对于可能存在重复键错误的批量插入,您需要设置continue_on_errorflag

使用此标志,即使发生错误,插入也会继续。最后一个错误将由getLastError 报告 - 你可以捕捉到它,或者如果你想触发并忘记将write concern 设置为 0。

from pymongo import *
client = MongoClient()
coll = client.test.test
coll.drop()

# Add a test document
coll.save({'_id': 1, 'hello': 'world'})
print(coll.count())

# Without the flag - Boom
coll.insert([{"_id": 1, "hello": "world"}, 
             {"_id": 2, "Howdy": "Worldy"}])
print(coll.count())

# With a write concern of 0 - no error but not saved.
coll.insert([{"_id": 1, "hello": "world"}, 
             {"_id": 2, "Howdy": "Worldy"}], w=0)
print(coll.count())

# Will error but will insert as well
coll.insert([{"_id": 1, "hello": "world"}, 
             {"_id": 2, "Howdy": "Worldy"}], continue_on_error=True)
print(coll.count())

# With a continue_on_error and write concern of 0 - will only error if theres 
# some socket or network error
coll.insert([{"_id": 1, "hello": "world"}, 
             {"_id": 2, "Howdy": "Worldy"},
             {"_id": 3, "Hi": "World"}], w=0,  continue_on_error=True)
print(coll.count())

【讨论】:

  • 谢谢。我自己也弄明白了。很高兴再次检查。
猜你喜欢
  • 2011-05-25
  • 2020-07-19
  • 2017-05-13
  • 2011-09-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多