How can I update and increment two fields in one command in MongoDB?

To update and increment two fields in one command in MongoDB, use the $inc operator with multiple field-value pairs in a single update operation. This allows you to increment multiple numeric fields atomically in one database call.

Syntax

db.collection.update(
    { query },
    { $inc: { field1: value1, field2: value2 } }
);

Create Sample Data

Let us first create a collection with documents ?

db.incrementDemo.insertOne({
    "Value1": 10,
    "Value2": 20
});
{
    "acknowledged": true,
    "insertedId": ObjectId("5cbdaf07de8cc557214c0e15")
}

Display all documents from the collection ?

db.incrementDemo.find().pretty();
{
    "_id": ObjectId("5cbdaf07de8cc557214c0e15"),
    "Value1": 10,
    "Value2": 20
}

Example: Increment Two Fields

Following is the query to increment two fields in one command ?

db.incrementDemo.update(
    {},
    { $inc: { Value1: 1, Value2: 1 } }
);
WriteResult({ "nMatched": 1, "nUpserted": 0, "nModified": 1 })

Verify Result

Let us check both fields have been incremented ?

db.incrementDemo.find().pretty();
{
    "_id": ObjectId("5cbdaf07de8cc557214c0e15"),
    "Value1": 11,
    "Value2": 21
}

Conclusion

The $inc operator allows you to increment multiple fields simultaneously in a single atomic operation. This approach is efficient and ensures data consistency when updating multiple numeric fields.

Updated on: 2026-03-15T00:51:22+05:30

343 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements