MongoDB Increment value inside nested array?


You can use positional operator $ for this. To understand the above concept, let us create a collection with the document. The query to create a collection with a document is as follows −

> db.incrementValueInNestedArrayDemo.insertOne(
   ... {"UniqueId":1,
      ... "StudentDetails":
      ... [
         ... {
            ... "StudentId":101,
            ... "StudentMarks":97
         ... },
         ... {
            ... "StudentId":103,
            ... "StudentMarks":99
         ... },
         ... {
            ... "StudentId":105,
            ... "StudentMarks":69
         ... },
         ... {
            ... "StudentId":107,
            ... "StudentMarks":59
         ... }
      ... ]
   ... }
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c77dd71fc4e719b197a12f7")
}

Display all documents from a collection with the help of find() method. The query is as follows −

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

The following is the output −

{
   "_id" : ObjectId("5c77dd71fc4e719b197a12f7"),
   "UniqueId" : 1,
   "StudentDetails" : [
      {
         "StudentId" : 101,
         "StudentMarks" : 97
      },
      {
         "StudentId" : 103,
         "StudentMarks" : 99
      },
      {
         "StudentId" : 105,
         "StudentMarks" : 92
      },
      {
         "StudentId" : 107,
         "StudentMarks" : 59
      }
   ]
}

Here is the query to increment a value in the nested array −

> db.incrementValueInNestedArrayDemo.update({UniqueId:1,"StudentDetails.StudentId":107},
{$inc:{"StudentDetails.$.StudentMarks":1}});
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

Let us check nested array value is incremented or not in the above collection with StudentId 107 −

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

The following is the output −

{
   "_id" : ObjectId("5c77dd71fc4e719b197a12f7"),
   "UniqueId" : 1,
   "StudentDetails" :
   [
      {
         "StudentId" : 101,
         "StudentMarks" : 97
      },
      {
         "StudentId" : 103,
         "StudentMarks" : 99
      },
      {
         "StudentId" : 105,
         "StudentMarks" : 92
      },
      {
         "StudentId" : 107,
         "StudentMarks" : 60
      }
   ]
}

Look at the sample output, the field name “StudentMarks” has been updated from 59 to 60 that means increments by 1.

Updated on: 30-Jul-2019

544 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements