Reputation: 31
i would like to update Elements that are nested inside of multiple Arrays, like:
{
_id: 1,
items:[{
item_id: 1,
desc:[{
desc_id: 1,
description: "Test entry"
},
{
desc_id: 2,
description: "Test entry 2"
}]
}]
}
How is it possible to edit "description" inside of the first desc element with Node and Mongoose. I tried:
Client.updateOne({"items.desc.desc_id": 1}, {$set:{"items.$.desc.$.description": "Other test entry"}})
Upvotes: 2
Views: 47
Reputation: 16033
If you want to update only the first desc
item try:
Client.updateOne({
"items.desc.desc_id": 1
},
{
$set: {
"items.$.desc.0.description": "Other test entry"
}
})
See how it works on the playground example - by index
EDIT:
You were using the positional $
operator which update the first match.
If you want to search the inner array by the desc_id
use the $[<identifier>]
:
db.collection.update(
{"items.desc.desc_id": 1},
{$set: {"items.$.desc.$[item].description": "Other test entry"}},
{arrayFilters: [{"item.desc_id": 1}]}
)
See how it works on the playground example by desc_id
But you are still using the positional $
operator for the external array, meaning you will only update the first match inside it.
To update all items according the desc_id, use the all positional operator $[]
for the external array:
db.collection.update(
{"items.desc.desc_id": 1},
{$set: {"items.$[].desc.$[item].description": "Other test entry"}},
{arrayFilters: [{"item.desc_id": 1}]}
)
See how it works on the playground example all items by desc_id
Upvotes: 1