使用 pymongo 更新和添加多个文档

Updating and Adding on multiple documents using pymongo

我有一个mongo数据库,有如下数据记录

[
    {"name" : "a", "email" : "dsda@test.com","ml_pred":"valid","hum_pred":"null", "score":0.92},
    {"name" : "b","email" : "eda@test.com","ml_pred":"invalid","hum_pred":"null", "score":0.2},
    {"name" : "c","email" : "edfr@test.com","ml_pred":"null","hum_pred":"null"},
    {"name" : "d","email" : "edsd@test.com","ml_pred":"null","hum_pred":"null"},
    {"name" : "e","email" : "edxz@test.com","ml_pred":"null","hum_pred":"null"}
]

这个数据是用insert_many in pymongo like

插入的
from pymongo import MongoClient
client = MongoClient('mongodb://testuser:testuser@mongo:27017/testdb?authSource=admin')
mydb = client["testdb"]    #Mongo database
mycol = mydb["todos"]    #Mongo Collection Name
mycol.insert_many(record)

如何使用以下数据bulk update and add new fields in a single step对第 3 和第 4 个文档进行操作

[
    {"name" : "c","email" : "edfr@test.com","ml_pred":"valid","hum_pred":"null","score":0.83},
    {"name" : "d","email" : "edsd@test.com","ml_pred":"invalid","hum_pred":"null","score":0.12}
]

您可以发送 2 个 updates.You 也可以使它们成为批量更新,或者您也可以编写一个管道更新来通过 1 个更新来完成这两项操作,但我认为您在这里不需要更复杂的东西。

两者匹配邮箱,然后更新2fields.Using更新$set运算符。

查询 1

Playmongo

update(
{"email": {"$eq": "edfr@test.com"}},
{"$set": {"ml_pred": "valid", "score": 0.83}})

查询 2

Playmongo

update(
{"email": {"$eq": "edsd@test.com"}},
{"$set": {"ml_pred": "invalid", "score": 0.12}})

编辑

我不使用 pymongo,我猜你需要类似 this 的东西,但这取决于你使用的 python 驱动程序,但在所有情况下都很简单

requests = [
    UpdateOne(...query1...),
    UpdateOne(...query2...)]
try:
    db.test.bulk_write(requests, ordered=False)
except BulkWriteError as bwe:
    pprint(bwe.details)

我通过(基于字段 email

添加了多个字段更新和添加
email_id=[data.pop("email") for data in datas]
operations=[UpdateOne({"email":email},{'$set':data}) for email ,data in zip(email_id,datas)]
mycol.bulk_write(operations)