Reputation: 51
I have the following data in my database mongodb
> db.poepledatas.find()
{ "_id" : ObjectId("5ef83e24b5b88209109affbd"), "name" : "eren", "age" : 30, "__v" : 0 }
{ "_id" : ObjectId("5ef85fef14e2da588c79683a"), "name" : "lixi", "age" : 30 }
{ "_id" : ObjectId("5ef866df14e2da588c79683b"), "name" : "deku", "age" : 29 }
i want to update the "age" field of the above documents with names eren and lixi to 40 is there a way to do this in one update command
i have been trying to do the following
personModel.updateMany({name:"eren",name:"lixi"},{age:40},function(err){
if(err){
console.log(err);
}
else{
console.log("updated");
}
});
But the above code only seems to change the age to 40 for only one record with the name "lixi"
> db.poepledatas.find()
{ "_id" : ObjectId("5ef83e24b5b88209109affbd"), "name" : "eren", "age" : 30, "__v" : 0 }
{ "_id" : ObjectId("5ef85fef14e2da588c79683a"), "name" : "lixi", "age" : 40 }
{ "_id" : ObjectId("5ef866df14e2da588c79683b"), "name" : "deku", "age" : 29 }
any way to update both the docs "name" eren and lixi to "age"=40 in one command?
Upvotes: 0
Views: 31
Reputation: 22276
Yes, use $in.
Also you had a minor syntax error in your update section. you did not use an update operator like $set
. As it will work as a replacement document with this syntax.
personModel.updateMany({name: {$in: ["lixi", "eren"]}}, {$set: {age: 40}}, function (err) {
if (err) {
console.log(err);
} else {
console.log("updated");
}
});
Upvotes: 1
Reputation: 22956
You have to have Or condition
{"$or" : [{name:"eren"}, {name:"lixi"}]}
Your update statement should be
{"$set" :{age:40}}
Upvotes: 0