Increment MongoDB value inside a nested array

MongoDBDatabaseBig Data Analytics

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
      }
   ]
}
raja
Published on 11-Apr-2019 15:03:05
Advertisements