Increment MongoDB value inside a nested array


To increment a value inside a nested array, use positional operator ($). Let us first create a collection with documents

> db.incrementInNestedArrayDemo.insertOne(
... {
...    "StudentId":100,
...    "ProjectDetails":
...    [
...       {"ProjectId":567778888,
...          "TeamSize":4
...       },
...       {
...          "ProjectId":67888999,
...          "TeamSize":2
...       }
...    ]
... }
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c9a6b7b15e86fd1496b38aa")
}

Following is the query to display all documents from a collection with the help of find() method

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

This will produce the following output

{
   "_id" : ObjectId("5c9a6b7b15e86fd1496b38aa"),
   "StudentId" : 100,
   "ProjectDetails" : [
      {
         "ProjectId" : 567778888,
         "TeamSize" : 4
      },
      {
         "ProjectId" : 67888999,
         "TeamSize" : 2
      }
   ]
}

Following is the query to increment value inside nested array

> db.incrementInNestedArrayDemo.update({ "StudentId" : 100, "ProjectDetails.ProjectId":67888999} , {$inc:{"ProjectDetails.$.TeamSize":1}});
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

Let us check that the field TeamSize is incremented by 1 or not. Following is the query

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

This will produce the following output

{
   "_id" : ObjectId("5c9a6b7b15e86fd1496b38aa"),
   "StudentId" : 100,
   "ProjectDetails" : [
      {
         "ProjectId" : 567778888,
         "TeamSize" : 4
      },
      {
         "ProjectId" : 67888999,
         "TeamSize" : 3
      }
   ]
}

Updated on: 30-Jul-2019

103 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements