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,
- Find Object with
id:1 - Find an object with
mail:[email protected]insidecommentsarray, - Update the
Commentof the particular Object
This is the query I tried to update but doesn't work
modal.findOneAndUpdate(
{ id: 1, comments: { mail: "[email protected]"} },
{
$set: {
"comments.$.Comment": "New Comment",
},
}
);
CodePudding user response:
change comments: { mail: "[email protected]"} to 'comments.mail': "[email protected]"
CodePudding user response:
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]"
}
]
})
