I found a StackOverflow Question that comes very close to answering my question, but not quite there.
Take this original question (modifying a document that is in an array) but assume that you do not have a specific change you wish to make. Instead, I have a dictionary of changes that I wish to make. Here is an example:
Original Document
{
_id: something,
recipients: [{id:1, name:"Andrey", isread:false}, {id:2, name:"John", isread:false}]
}
Changes to be made
{
isread: true,
fullname: 'jonathan'
}
How can I apply this dictionary of changes to John (id:2)? Incase it is relevant, I am using the MongoDB-Node.JS Driver Thank you
Just like in the question you referenced, you need to use the $
positional operator, but with update
in this case:
collection.update({_id:something, 'recipients.id': 2}, {$set: {'recipients.$': {
isread: true,
fullname: 'jonathan'
}}}, function (err) {...
EDIT
To not replace the whole array element object you'd have to do something like this:
collection.update({_id:something, 'recipients.id': 2}, {$set: {
'recipients.$.isread': true,
'recipients.$.fullname': 'jonathan'
}}, function (err) {...