Increment a value in a MongoDB nested object?


To increment a value in nested object, you can use $inc operator. Let us first implement the following query to create a collection with documents

>db.incrementValueDemo.insertOne({"StudentName":"Larry","StudentCountryName":"US","StudentDetails":[{"StudentSubjectName":"Math","StudentMathMarks":79}]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c986ca0330fd0aa0d2fe4a2")
}

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

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

This will produce the following output

{
   "_id" : ObjectId("5c986ca0330fd0aa0d2fe4a2"),
   "StudentName" : "Larry",
   "StudentCountryName" : "US",
   "StudentDetails" : [
      {
         "StudentSubjectName" : "Math",
         "StudentMathMarks" : 79
      }
   ]
}

Following is the query to increment a value in nested object. The marks would get incremented here

> db.incrementValueDemo.update( {"StudentDetails.StudentSubjectName":"Math"}, { $inc : {
   "StudentDetails.$.StudentMathMarks" : 1 } });
   WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

Following is the query to check the value is incremented or not

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

This will produce the following output

{
   "_id" : ObjectId("5c986ca0330fd0aa0d2fe4a2"),
   "StudentName" : "Larry",
   "StudentCountryName" : "US",
   "StudentDetails" : [
      {
         "StudentSubjectName" : "Math",
         "StudentMathMarks" : 80
      }
   ]
}

Updated on: 30-Jul-2019

330 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements