Increment a property value of an element in array object with MongoDB

To increment a property value of an element in a MongoDB array, use the $inc operator combined with the $ positional operator. The $ operator identifies the matched array element, while $inc increases the specified field by a given value.

Syntax

db.collection.update(
    { "arrayField.property": "matchValue" },
    { $inc: { "arrayField.$.targetProperty": incrementValue } }
);

Sample Data

Let us create a collection with student details ?

db.demo97.insertOne({
    "Details": [
        {
            "Name": "Chris",
            "Marks": 45
        },
        {
            "Name": "Bob",
            "Marks": 88
        }
    ]
});
{
    "acknowledged": true,
    "insertedId": ObjectId("5e2d6d24b8903cdd865577af")
}

Display the current document ?

db.demo97.find();
{
    "_id": ObjectId("5e2d6d24b8903cdd865577af"),
    "Details": [
        { "Name": "Chris", "Marks": 45 },
        { "Name": "Bob", "Marks": 88 }
    ]
}

Example: Increment Bob's Marks by 10

db.demo97.update(
    { "Details.Name": "Bob" },
    { $inc: { "Details.$.Marks": 10 } }
);
WriteResult({ "nMatched": 1, "nUpserted": 0, "nModified": 1 })

Verify Result

db.demo97.find();
{
    "_id": ObjectId("5e2d6d24b8903cdd865577af"),
    "Details": [
        { "Name": "Chris", "Marks": 45 },
        { "Name": "Bob", "Marks": 98 }
    ]
}

Key Points

  • The $ positional operator targets the first matching array element
  • $inc can increment by positive or negative values (use negative to decrement)
  • The target field must be a numeric type for $inc to work

Conclusion

Use $inc with the $ positional operator to increment numeric properties within array objects. This approach efficiently updates specific array elements without affecting other elements in the array.

Updated on: 2026-03-15T01:54:21+05:30

558 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements