0
0
MongodbHow-ToBeginner · 3 min read

How to Use $inc Operator in MongoDB: Syntax and Examples

In MongoDB, the $inc operator is used to increase or decrease the value of a numeric field in a document. You use it inside an update command by specifying the field and the amount to increment or decrement. For example, { $inc: { score: 1 } } adds 1 to the score field.
📐

Syntax

The $inc operator takes an object where each key is the field name to update, and the value is the amount to add (positive or negative). It works only on numeric fields.

  • Field name: The numeric field you want to change.
  • Increment value: The number to add (use negative to subtract).
mongodb
db.collection.updateOne(
  { <filter> },
  { $inc: { <field1>: <amount1>, <field2>: <amount2>, ... } }
)
💻

Example

This example shows how to increase the views field by 5 in a document where _id is 1.

mongodb
db.posts.updateOne(
  { _id: 1 },
  { $inc: { views: 5 } }
)

// After update, if views was 10, it becomes 15
Output
{ "acknowledged" : true, "matchedCount" : 1, "modifiedCount" : 1 }
⚠️

Common Pitfalls

Common mistakes when using $inc include:

  • Trying to increment a field that is not numeric (e.g., a string), which causes an error.
  • Using $inc on a field that does not exist yet; MongoDB will create the field and set it to the increment value.
  • Forgetting to use $inc inside an update operator object, which leads to replacing the whole document.
mongodb
/* Wrong: Replaces whole document instead of incrementing */
db.posts.updateOne(
  { _id: 1 },
  { views: 5 }  // Missing $inc
)

/* Right: Correctly increments views by 5 */
db.posts.updateOne(
  { _id: 1 },
  { $inc: { views: 5 } }
)
📊

Quick Reference

UsageDescription
{ $inc: { field: 1 } }Increase field by 1
{ $inc: { field: -1 } }Decrease field by 1
{ $inc: { field1: 2, field2: -3 } }Increment multiple fields at once
{ $inc: { newField: 10 } }Creates newField with value 10 if it doesn't exist

Key Takeaways

Use $inc inside an update command to add or subtract from numeric fields.
$inc creates the field if it does not exist, setting it to the increment value.
Do not use $inc on non-numeric fields to avoid errors.
Always include $inc inside an update operator object to avoid replacing documents.
You can increment multiple fields in one update using $inc.