Increment a field in MongoDB document which is embedded?


Let’s say, here we are incrementing StudentScores for MongoDB which is inside StudentDetails −

... "StudentScores": {
...    "StudentMathScore": 90,
...    "StudentMongoDBScore": 78
... }

Let us first create a collection with documents −

> db.embeddedValueIncrementDemo.insertOne(
...    {
...       "StudentDetails": {
...          "StudentScores": {
...             "StudentMathScore": 90,
...             "StudentMongoDBScore": 78
...          }
...       }
...    }
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cd2b670345990cee87fd896")
}

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

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

This will produce the following output −

{
   "_id" : ObjectId("5cd2b670345990cee87fd896"),
   "StudentDetails" : {
      "StudentScores" : {
         "StudentMathScore" : 90,
         "StudentMongoDBScore" : 78
      }
   }
}

Following is the query to increment embedded value. Here, we are incrementing StudentMongoDBScore −

> db.embeddedValueIncrementDemo.update({ _id: new ObjectId("5cd2b670345990cee87fd896") }, { $inc: { "StudentDetails.StudentScores.StudentMongoDBScore": 20 } }, { upsert: true, safe: true }, null);
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

Let us check all the documents once again −

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

This will produce the following output −

{
   "_id" : ObjectId("5cd2b670345990cee87fd896"),
   "StudentDetails" : {
      "StudentScores" : {
         "StudentMathScore" : 90,
         "StudentMongoDBScore" : 98
      }
   }
}

Updated on: 30-Jul-2019

113 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements