How to Use $inc Operator in MongoDB for Incrementing Values
In MongoDB, use the
$inc operator to increase or decrease the value of a numeric field in a document. It modifies the field by the specified amount without replacing the whole document. For example, { $inc: { score: 1 } } adds 1 to the current value of score.Syntax
The $inc operator takes an object where keys are field names and values are the amounts to increment or decrement. Positive values increase the field, negative values decrease it.
- Field: The numeric field to update.
- Value: The number to add (can be negative to subtract).
mongodb
db.collection.updateOne(
{ <filter> },
{ $inc: { <field1>: <amount1>, <field2>: <amount2>, ... } }
)Example
This example shows how to increment the views field by 1 in a document where _id is 1.
mongodb
db.articles.updateOne(
{ _id: 1 },
{ $inc: { views: 1 } }
)
// To decrement views by 2:
db.articles.updateOne(
{ _id: 1 },
{ $inc: { views: -2 } }
)Output
{ "acknowledged" : true, "matchedCount" : 1, "modifiedCount" : 1 }
Common Pitfalls
Common mistakes when using $inc include:
- Trying to increment a field that is not numeric, which causes an error.
- Using
$incon a field that does not exist will create the field with the increment value. - Passing a non-numeric value to
$incwill fail.
Always ensure the field is numeric or absent before using $inc.
mongodb
/* Wrong: incrementing a string field */ db.users.updateOne( { _id: 1 }, { $inc: { name: 1 } } // Error: cannot apply $inc to string ) /* Correct: incrementing a numeric field */ db.users.updateOne( { _id: 1 }, { $inc: { age: 1 } } )
Quick Reference
| Usage | Description |
|---|---|
| { $inc: { field: 1 } } | Increment field by 1 |
| { $inc: { field: -1 } } | Decrement field by 1 |
| { $inc: { field1: 2, field2: -3 } } | Increment field1 by 2 and decrement field2 by 3 |
| Using $inc on non-existing field | Creates the field with the increment value |
Key Takeaways
Use $inc to add or subtract numeric values in a document field without replacing the whole document.
$inc works only on numeric fields; applying it to non-numeric fields causes errors.
If the field does not exist, $inc creates it with the increment value.
You can increment multiple fields at once by specifying them inside $inc.
Always verify the field type before using $inc to avoid update failures.