$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.

CategoryUpdate Field
MongoDB Version1.0+
Example Languagemongosh (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

📚 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.
Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏