Increment a value in a MongoDB nested object?

MongoDBDatabaseBig Data Analytics

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
      }
   ]
}
raja
Published on 11-Apr-2019 08:47:01
Advertisements