Update objects in a MongoDB documents array (nested updating)?


To update the objects in a document’s array, you need to use update() method. To understand the update() method, let us create a collection with document. The query to create a collection with document is as follows:

> db.updateObjects.insertOne({"CustomerId":1,"CustomerName":"Larry","TotalItems":100,
... "ItemDetails":[
... {
... "NameOfItem":"Item_1",
... "Amount":450
... },
... {
... "NameOfItem":"Item_2",
... "Amount":500
... },
... {
... "NameOfItem":"Item_3",
... "Amount":200
... }
... ]
... }
... );

The following is the output:

{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c6d688b0c3d5054b766a769")
}

Now you can display documents from a collection with the help of find() method. The query is as follows:

> db.updateObjects.find().pretty();

The following is the output displaying the documents from the collection created above:

{
   "_id" : ObjectId("5c6d688b0c3d5054b766a769"),
   "CustomerId" : 1,
   "CustomerName" : "Larry",
   "TotalItems" : 100,
   "ItemDetails" : [
      {
         "NameOfItem" : "Item_1",
         "Amount" : 450
      },
      {
         "NameOfItem" : "Item_2",
         "Amount" : 500
      },
      {
         "NameOfItem" : "Item_3",
         "Amount" : 200
      }
   ]
}

Increment “Amount”:200 with value 130. The query is as follows. Here, we have used the $inc operator to increment the value of a field:

> db.updateObjects.update({"CustomerId":1,"ItemDetails.NameOfItem":"Item_3"},
{$inc:{"ItemDetails.$.Amount":130}},
... false,true);
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

We have successfully updated incremented the value. Let us display the document from the collection. The query is as follows:

> db.updateObjects.find().pretty();

The following is the output:

{
   "_id" : ObjectId("5c6d688b0c3d5054b766a769"),
   "CustomerId" : 1,
   "CustomerName" : "Larry",
   "TotalItems" : 100,
   "ItemDetails" : [
      {
         "NameOfItem" : "Item_1",
         "Amount" : 450
      },
      {
         "NameOfItem" : "Item_2",
         "Amount" : 500
      },
      {
         "NameOfItem" : "Item_3",
         "Amount" : 330
      }
   ]
}

Look at the sample output, the Amount 200 is incremented with 130, which is 330 now.

Updated on: 30-Jul-2019

588 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements