【问题标题】:Pymongo: Bulk update with $setOnInsert errorPymongo:使用 $setOnInsert 错误进行批量更新
【发布时间】:2014-12-13 05:45:13
【问题描述】:

我正在尝试进行批量更新,同时保留特定字段的状态。 在我的代码中,我要么创建一个文档,要么将“东西”添加到列表中。

#init bulk
data = [...]
bulkop = col.initialize_ordered_bulk_op()
for d in data:
   bulkop.find({'thing':d}).upsert().update({'$setOnInsert':{'status':0},'$push':{'stuff':'something'},'$inc': { 'seq': 1 }})
bulkop.execute()

但是,我在尝试此操作时遇到错误。 错误:pymongo.errors.BulkWriteError:发生批处理操作错误

没有 $setOnInsert':{'status':0} 添加它可以正常工作,但我需要这个来确保状态变量没有得到更新。

【问题讨论】:

  • 解决方案:更新我的mongodb版本后,它开始工作了。

标签: python mongodb pymongo


【解决方案1】:

我认为您使用的是 pymongo 3.x,上面的代码适用于 pymongo 2.x。试试这个...

from pymongo import MongoClient, UpdateMany
client = MongoClient(< connection string >)
db = client[test_db]
col = db[test]
docs = [doc_1,doc_2,doc_3,....,doc_n]

requests = [UpdateMany({ },{'$setOnInsert':{'status':0},"$set":{"$push":docs}}, upsert = True)]
result = col.bulk_write(requests)
print(result.inserted_count)

这里的空{}表示更新所有记录。

希望这会有所帮助...

【讨论】:

    猜你喜欢
    • 2017-07-12
    • 2020-07-10
    • 2016-05-30
    • 2012-08-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多