Reputation: 23
User:
{
_id: "userID",
array_1:[],
array_2:[]
}
I need to do two updates to this document:
array_1
contains objects with unique id
property. I need to find one where id=targetID
and replace it with the newObject
, like this:User.updateOne(
{
_id: userID,
"array_1.id": targetID
},
{
"$set":{"array_1.$":newObject}
}
)
array_2
contains objects, where multiple objects can have same id
values. I need to update 2 properties of all objects in the array_2
where id=targetID
, like this:User.updateOne(
{
_id: userID,
"array_2.id": targetID
},
{
"$set": {
"array_2.$[elem].property_1": new_property_1,
"array_2.$[elem].property_2": new_property_2
}
},
{
"arrayFilters": [{ "elem.id": targetID }],
"multi": true
}
)
These two work fine if I run it separately, but how do I combine both in one function?
Upvotes: 2
Views: 37
Reputation: 36104
You can combine it using arrayFilters, same as you did nin second query,
arr1
and use it to update object,await User.updateOne(
{ _id: userID },
{
$set: {
"array_1.$[arr1]": newObject,
"array_2.$[elem].property_1": new_property_1,
"array_2.$[elem].property_2": new_property_2
}
},
{
arrayFilters: [
{ "elem.id": targetID },
{ "arr1._id": targetID }
]
}
)
Upvotes: 1