Lets say we have this document:
{
"_id" : ObjectId("4faaba123412d654fe83hg876"),
"items" : [
{
"name" : "item_one",
"bought" : true
},
{
"name" : "my_item",
"bought" : true
},
{
"name" : "my_item_three",
"bought" : true
}
]
}
For example how can I modify the first 2 objects of the array and set their "bought" to false. Or in other words how could I change properties of the first n objects.
I thought I could first do a db.findOne() with this ID than take the items and use a function that will change the values and then set the whole item to this new array that this function returns.
That would probably do the work but is there a faster and nicer method? Is there a way to do it if I know the number of objects I want to change, so it will not be n but 5 for example.
.findOne()or similar logic and then alter the content of the document and.save()it back or similar. This is not a "great" pattern though as other writes could have occurred on the document in the time between when you read it and when you save it. If you need to do this kind of updating to "multiple" array elements at once then you are best to consider a different model, ie collection instead of embedded.