如何使用批量操作更新 mongodb 中的文档?

How to update documents in mongdb using bulk operation?

我正在尝试使用 python 和 tornado 访问单个函数内的单个 table。

根据对我上一个问题的建议,我正在尝试使用 mongodb 中可用的 Bulk 操作来做到这一点。我尝试插入成功,但在更新过程中出现错误。

我的密码是

bulk = db.Test.initialize_unordered_bulk_op()
print("1")
bulk.insert({"test":"we"})
# bulk.find({"test": "we"})
bulk.update({"test": "we"},{'$set':{"test": "false"}},{'$unset':{"Cid"}})
t = bulk.execute()
print(t)

查询有问题吗?

并且在尝试打印 find 操作的答案时得到

<tornado.concurrent.Future object at 0x02ED2630>

谁能指导我如何进行批量操作。

你需要.find()你想要的.update()

bulk.find({"test": "we"}).update({'$set': {"test": "false"}, '$unset': {"Cid", ""}})

您也可以在 collection 中查找文档,只需使用 .find method which returns a Cursor object. You will then need to iterate over the cursor or use list to return the documents. That being said if know that your query will return only one document then what you need is the .find_one() 方法即可。

在您打印 bulk.find doesn't make any sense because you are inserting the document, updating using the same instance of BulkOperationBuilder which means that all your operations will be sent to the server after .execute()

的结果中

如果您使用的是 Motor,则需要 "yield" bulk.execute 返回的 Future 以等待其完成并获得结果:

@gen.coroutine
def f():
    bulk = db.Test.initialize_unordered_bulk_op()
    print("1")
    bulk.insert({"test":"we"})
    # bulk.find({"test": "we"})
    bulk.update({"test": "we"},{'$set':{"test": "false"}},{'$unset':{"Cid"}})
    t = yield bulk.execute()
    print(t)

电机是异步的;为了等待与数据库服务器通信的任何 Motor 方法完成,您必须将回调传递给该方法,或者将 Future 交给方法 returns.

有关更多信息,请参阅教程:

http://motor.readthedocs.org/en/stable/examples/bulk.html#ordered-bulk-write-operations