使用pymongo使用特定过滤器更新多个文档

时间:2017-08-14 10:44:56

标签: python mongodb pymongo

我想使用pymongo更新mongoDB数据库中的多个文档。我有这些数据:

data_to_be_updated = [
    {"sourceID" : 6, "source" : "test", "name" : "simon"},
    {"sourceID" : 8, "source" : "test", "name" : "greg"},
    {"sourceID" : 9, "source" : "test", "name" : "julie"},
    {"sourceID" : 10, "source" : "test", "name" : "john"}
    ]
sourceIDs = [6, 8, 9, 10]

我想更新data_to_be_inserted中的每个元素,按照sourceID过滤它们。我尝试使用update_many函数,但它会更新与单个过滤器匹配的所有文档。我当然可以像这样使用for循环:

for item in data_to_be_updated:
    collection.update_one({"sourceID": item["sourceID"]}, item})

上述方法用于多次调用。如何在一次调用数据库时实现相同的目标?

1 个答案:

答案 0 :(得分:2)

使用bulk_write。这样的事情,具体取决于需要更新的字段:

from pymongo.operations import UpdateOne

data_to_be_updated = [
    {"sourceID": 6, "source": "test", "name": "simon"},
    {"sourceID": 8, "source": "test", "name": "greg"},
    {"sourceID": 9, "source": "test", "name": "julie"},
    {"sourceID": 10, "source": "test", "name": "john"}
]

result = collection.bulk_write([
    UpdateOne(filter={'sourceID': d['sourceID']},
              update={'$set': {'name': d['name'],
                               'source': d['source']}})
    for d in data_to_be_updated])

print(result.bulk_api_result)