Increment only a single value in MongoDB document?

To increment only a single value in a MongoDB document, use the $inc operator with the update() method. The $inc operator increases the value of a field by the specified amount.

Syntax

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

Create Sample Data

Let us create a collection with documents containing Score values ?

db.demo698.insertMany([
    { Score: 78 },
    { Score: 56 },
    { Score: 65 },
    { Score: 88 }
]);
{
    "acknowledged": true,
    "insertedIds": [
        ObjectId("5ea6d8a4551299a9f98c9398"),
        ObjectId("5ea6d8a7551299a9f98c9399"),
        ObjectId("5ea6d8aa551299a9f98c939a"),
        ObjectId("5ea6d8b0551299a9f98c939b")
    ]
}

Display all documents from the collection ?

db.demo698.find();
{ "_id": ObjectId("5ea6d8a4551299a9f98c9398"), "Score": 78 }
{ "_id": ObjectId("5ea6d8a7551299a9f98c9399"), "Score": 56 }
{ "_id": ObjectId("5ea6d8aa551299a9f98c939a"), "Score": 65 }
{ "_id": ObjectId("5ea6d8b0551299a9f98c939b"), "Score": 88 }

Example: Increment Single Value

Increment the Score field by 12 for a specific document ?

db.demo698.update(
    { _id: ObjectId("5ea6d8b0551299a9f98c939b") },
    { $inc: { Score: 12 } }
);
WriteResult({ "nMatched": 1, "nUpserted": 0, "nModified": 1 })

Verify Result

Display all documents to verify the increment operation ?

db.demo698.find();
{ "_id": ObjectId("5ea6d8a4551299a9f98c9398"), "Score": 78 }
{ "_id": ObjectId("5ea6d8a7551299a9f98c9399"), "Score": 56 }
{ "_id": ObjectId("5ea6d8aa551299a9f98c939a"), "Score": 65 }
{ "_id": ObjectId("5ea6d8b0551299a9f98c939b"), "Score": 100 }

Key Points

  • The $inc operator works with numeric values only.
  • Use a positive value to increment, negative value to decrement.
  • Only the matched document gets updated, other documents remain unchanged.

Conclusion

The $inc operator provides an efficient way to increment specific numeric fields in MongoDB documents. It atomically updates only the target field without affecting other document properties.

Updated on: 2026-03-15T03:39:05+05:30

186 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements