Reputation: 21
I've got a document like this,
[
{
"id": 1,
"comments": [
{
"mail": "[email protected]",
"Comment": "This product well worth the money"
}
{
"mail": "[email protected]",
"Comment": "Excellent Product"
}
]
},
{
"id": 2,
"comments": [
{
"mail": "[email protected]",
"Comment": "This product well worth the money"
}
{
"mail": "[email protected]",
"Comment": "Excellent Product"
}
]
}
]
Now I need to change only the Comment
with mail
"[email protected]" which is inside the comments
array of the object having the id
"1".
So the hierarchy looks like,
id:1
mail:[email protected]
inside comments
array,Comment
of the particular ObjectThis is the query I tried to update but doesn't work
modal.findOneAndUpdate(
{ id: 1, comments: { mail: "[email protected]"} },
{
$set: {
"comments.$.Comment": "New Comment",
},
}
);
Upvotes: 0
Views: 125
Reputation: 51485
You can use arrayFilters
to update the nested document in the array as well.
db.collection.update({
id: 1
},
{
$set: {
"comments.$[comment].Comment": "New Comment",
}
},
{
arrayFilters: [
{
"comment.mail": "[email protected]"
}
]
})
Upvotes: 1
Reputation: 1086
change comments: { mail: "[email protected]"}
to 'comments.mail': "[email protected]"
Upvotes: 2