MongoDB - Update objects in a document's array | MongoDB update object in Array

Sometime in MongoDB, we need to update the object in the array for the particular matching document. We need to update either the first matching object or all the matching objects in the array. Let me give you an example of the documents. Let say I have the following collection whose name is items.

Now I wanted to update the latest price of the item whose name is "my_item_two".

We achieve this through the positional operator ($). The positional operator is used to performing the operation on the particular position. Let me write the query for that:

This will update the first matching array element but sometime we may need to update all the matching array elements and we can do that by using the $[]. The all positional operator $[] indicates that the update operator should modify all elements in the specified array field.


Share This:

Leave a Reply

Your email address will not be published. Required fields are marked *