Increment a value in a MongoDB nested object?

To increment a value in a MongoDB nested object, use the $inc operator combined with the $ positional operator to target the specific nested element and increment its numeric value.

Syntax

db.collection.update(
    {"nestedArray.field": "matchValue"},
    { $inc: { "nestedArray.$.fieldToIncrement": incrementValue } }
);

Create Sample Data

Let us create a collection with a document containing nested array objects ?

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

Display Current Document

db.incrementValueDemo.find().pretty();
{
    "_id": ObjectId("5c986ca0330fd0aa0d2fe4a2"),
    "StudentName": "Larry",
    "StudentCountryName": "US",
    "StudentDetails": [
        {
            "StudentSubjectName": "Math",
            "StudentMathMarks": 79
        }
    ]
}

Increment Nested Value

Increment the Math marks by 1 using $inc operator ?

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

Verify Result

db.incrementValueDemo.find().pretty();
{
    "_id": ObjectId("5c986ca0330fd0aa0d2fe4a2"),
    "StudentName": "Larry",
    "StudentCountryName": "US",
    "StudentDetails": [
        {
            "StudentSubjectName": "Math",
            "StudentMathMarks": 80
        }
    ]
}

Key Points

  • The $ positional operator identifies the first matching array element.
  • $inc can increment by positive or negative values (use negative to decrement).
  • The field being incremented must contain a numeric value.

Conclusion

Use $inc with the $ positional operator to increment numeric values in nested objects. The query condition identifies the array element, and $inc performs the increment operation on the specified nested field.

Updated on: 2026-03-15T00:24:24+05:30

538 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements