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.

  ...  Read More

Share This:


Push multiple objects into MongoDB array document | Append Multiple Objects to an Array in MongoDB

Normally we use $push to push or append the element or object into an array in mongoDB. But sometime we may need to push the multiple objects into mongoDB array document. Here below I'll try to explain how we can do that.

Let say I have a collection of favorite products and the collection name is favorite_products.

Now in the above document, I wanted to push/append the multiple user objects into the users array whose product id is 124.



 ...  Read More

Share This:


MongoDB distinct with array of objects | Getting distinct values from object array MongoDB

Let say we have a collection transactions which contains some document and documents contain payments which is array of objects.
Now my task is to get the unique types in payments array of every document.

Expected Result: Debit Card, Internet Banking, Credit Card, UPI



which is unique values of payment types in transctions collection and the MongoDB query for that is given below:

Here we first unwind the data so that every payments array can be converted to objects and then we are grouping the type of payments document in transctions collection. ...  Read More

Share This: