Reputation: 83
I have been trying to update my MongoDB tables by '_id' using updateMany. I couldn't find a way or command in MongoDB documentary the way I want to update. I use python to manipulate the data.
Here is my entries:
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
}
I want to update three of the entries at once by using updateMany(). My attempt is as followed:
Tbl.updateMany({
'_id': {
'$in': ["001",
"002",
"003"]
}
}, {
'$set': [{'age': 25, 'salary': 35000},
{'age': 23, 'salary': 25000},
{'age': 27, 'salary': 45000}]
})
I would like to know if I am able to update many entries in MongoDB like this. Thank you for your time in advance.
Upvotes: 1
Views: 654
Reputation: 83
Following is the correct command
Tbl.bulkWrite([pymongo.UpdateOne(
{ "name" : "Alisha" }, { "$set" : {'age': 25, 'salary': 35000}}),
pymongo.UpdateOne(
{ "name" : "Ivan" }, { "$set" : {'age': 23, 'salary': 25000}})])
Upvotes: 0
Reputation: 21
UpdateMany won't work for multiple set queries. It will only take one set query for multiple documents. Either use a loop with updateOne query or if you want to do it in single query use bulkWrite 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}
} } },
])
Upvotes: 1