PyMongo:如何在不使用更新运算符的情况下 update_many ?

don*_*208 2 python mongodb pymongo

当修改不能直接使用更新运算符表达时,更新多个文档的最佳方法是什么?

这是我到目前为止所拥有的:

def modify_doc(doc):
    // modify doc in place
    return modified_doc

for doc in db.collection.find({}):
    mod_doc = modify_doc(doc)
    collection.replace_one({'_id': mod_doc._id}, new_doc)
Run Code Online (Sandbox Code Playgroud)

我也在考虑:

def get_update_instructions(doc):
    mod_doc = modify_doc(doc)
    // take diff between doc and mod_doc and create update_instructions
    return update_instructions

for doc in db.collection.find({}):
    update_instructions = get_update_instructions(doc)
    collection.update_one({'_id': mod_doc._id}, update_instructions)
Run Code Online (Sandbox Code Playgroud)

有没有更好的办法?

Cor*_*pto 5

您仍然可以应用批量更新,这有点类似于在 SQL 数据库中执行批量事务(但没有回滚,所以要小心)。这是通过对象bulk_write上存在的方法巧妙地记录的pymongo.Collection。基本方法是通过创建 UpdateOne 实例并将其放入列表中来手动聚合更新操作。然后,当您准备好写入数据库时​​,您可以调用bulk_write

作为基于您当前代码的基本示例:

from pymongo import UpdateOne

def modify_doc(doc):
    // modify doc in place
    return modified_doc

bulk_updates = []

for doc in db.collection.find({}):
    mod_doc = modify_doc(doc)
    bulk_updates.append(UpdateOne({'_id': mod_doc._id}, mod_doc))

db.collection.bulk_write(bulk_updates)
Run Code Online (Sandbox Code Playgroud)

对于可以与bulk_write方法一起使用的更多操作,这里是文档链接:http://api.mongodb.com/python/current/api/pymongo/operations.html