使用pymong更新具有特定过滤器的多个文档

2024-09-29 21:31:22 发布

您现在位置:Python中文网/ 问答频道 /正文

我想用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循环:

^{pr2}$

上面的方法用于许多调用。如何在对数据库的单个调用中实现相同的目标?在


Tags: to数据name文档test数据库sourcedata
1条回答
网友
1楼 · 发布于 2024-09-29 21:31:22

使用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)

相关问题 更多 >

    热门问题