MongoDB updateMany命令命令、MongoDB、updateMany

2023-09-03 08:09:23 作者:曲未成调

我一直在尝试使用updatMany通过‘_id’更新我的MongoDB表。我在MongoDB纪录片中找不到我想要更新的方式或命令。我使用PYTHON来操作数据。

以下是我的条目:

Tbl = {
    "_id": {
        "$oid": "001"
    },
    "name": "Alisha",
    "age": 24,
    "userid": 378824346,
    "salary": 30000
},
{
    "_id": {
        "$oid": "002"
    },
    "name": "Lana",
    "age": 22,
    "userid": 378824347,
    "salary": 20000
},
{
    "_id": {
        "$oid": "003"
    },
    "name": "Ivan",
    "age": 26,
    "userid": 378824348,
    "salary": 40000
},
{
    "_id": {
        "$oid": "004"
    },
    "name": "Yuri",
    "age": 25,
    "userid": 378824349,
    "salary": 34000
}
使用Python操作MongoDB

我想通过使用updatMany()一次更新三个条目。我的尝试如下:


Tbl.updateMany({
    '_id': {
        '$in': ["001", 
                "002", 
                "003"]
    }
}, {
    '$set': [{'age': 25, 'salary': 35000}, 
             {'age': 23, 'salary': 25000}, 
             {'age': 27, 'salary': 45000}]
})

我想知道我是否能够像这样更新MongoDB中的许多条目。感谢您提前抽出时间。

推荐答案

UpdateMany不适用于多个集合查询。多张单据只需一套查询即可。 或者对update One查询使用循环,或者如果要在单个查询中执行此操作,请使用BulkWite https://docs.mongodb.com/manual/reference/method/db.collection.bulkWrite/

Tbl.bulkWrite([
    { 
      updateOne : {
     "filter" : { "_id" : ""001"" },
     "update" : { $set : {'age': 25, 'salary': 35000} 
     } } },
    { 
      updateOne : {
     "filter" : { "_id" : ""002"" },
     "update" : { $set : {'age': 23, 'salary': 25000} 
    } } },
])