$inc (Increment)
Last updated: 2026-10-09
$inc (Increment)
$inc increases (or decreases) a numeric field by a specified amount, creating the field with the increment if it does not exist. `{ $inc: { views: 1 } }` adds 1 to views; `{ $inc: { stock: -5 } }` subtracts 5. It is atomic, ideal for counters and view counts, avoiding read-modify-write races.
| Category | Update Field |
|---|---|
| MongoDB Version | 1.0+ |
| Example Language | mongosh (Shell) |
📝 Syntax
{ $inc: { <field>: <amount> } }
▶ Example
Run the commands below in your local mongosh (requires a running mongod):
// $inc: views +1, stock -5
db.articles.updateOne(
{ _id: 1 },
{ $inc: { views: 1 } }
)
db.products.updateOne(
{ _id: 2 },
{ $inc: { stock: -5 } }
)
Output:
// When the field is missing: views is created as 1; stock decreases by 5
📌 Notes
- Only numeric types supported; $inc on a non-numeric field throws an error
- An increment of 0 still creates the field if missing
- $inc is atomic; no separate find-then-update needed
🏷️ Related Tags
💡 Related Cases
Hands-On: CRUD for a Blog Comment System
Transaction Processing: ACID and Multi-Document Consistency
Document Update: A Detailed Explanation of `updateOne` and `updateMany`
📚 Related Tutorials
❓ FAQ
QCan $inc operate on strings?
ANo. $inc accepts only numeric types; using it on strings throws. For string concatenation use $concat (aggregation) or read-then-write.
QWhat happens when $inc targets a missing field?
AIf the field does not exist, $inc treats its initial value as 0 and creates it with the increment amount. The field must be numeric or an error is raised.
QCan $inc decrement a value?
AYes, pass a negative amount, e.g. { $inc: { score: -5 } } decrements score by 5. $inc is atomic, ideal for counters and leaderboards under concurrency.