Increment a field in MongoDB document which is embedded?

To increment a field in a MongoDB document that is embedded within nested objects, use the $inc operator with dot notation to specify the path to the embedded field.

Syntax

db.collection.update(
    { "query": "condition" },
    { $inc: { "parent.child.field": incrementValue } }
);

Sample Data

Let's create a document with embedded StudentScores inside StudentDetails:

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

Example: Increment Embedded Field

Let's increment the StudentMongoDBScore by 20 points using dot notation:

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

Verify Result

db.embeddedValueIncrementDemo.find().pretty();
{
    "_id": ObjectId("5cd2b670345990cee87fd896"),
    "StudentDetails": {
        "StudentScores": {
            "StudentMathScore": 90,
            "StudentMongoDBScore": 98
        }
    }
}

Key Points

  • Use dot notation to navigate through nested objects: "parent.child.field"
  • The $inc operator can increment by positive or negative values
  • If the field doesn't exist, $inc creates it with the increment value

Conclusion

Use dot notation with the $inc operator to increment embedded fields in MongoDB. The path "StudentDetails.StudentScores.StudentMongoDBScore" navigates through the nested structure to modify the target field efficiently.

Updated on: 2026-03-15T01:02:59+05:30

244 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements