The $inc operator is used to add or subtract a number from a field's current value in a document. It helps update numbers easily without replacing the whole value.
0
0
$inc operator for incrementing in MongoDB
Introduction
When you want to increase a user's score after they complete a task.
When you need to decrease the stock quantity after a sale.
When you want to count how many times an event happens by adding 1 each time.
When you want to adjust a balance by adding or subtracting an amount.
When you want to update a numeric field without fetching the whole document first.
Syntax
MongoDB
db.collection.updateOne(
{ <filter> },
{ $inc: { <field1>: <amount1>, <field2>: <amount2>, ... } }
)The $inc operator takes an object where keys are field names and values are numbers to add (positive) or subtract (negative).
If the field does not exist, $inc will create it and set it to the increment value.
Examples
Adds 5 to Alice's score field.
MongoDB
db.users.updateOne({ name: "Alice" }, { $inc: { score: 5 } })Subtracts 3 from the stock of the Pen product.
MongoDB
db.products.updateOne({ item: "Pen" }, { $inc: { stock: -3 } })Increments the pageViews count by 1.
MongoDB
db.counters.updateOne({ _id: "pageViews" }, { $inc: { count: 1 } })Sample Program
This example first adds a document with 10 notebooks. Then it increases the quantity by 5 using $inc. Finally, it shows the updated document.
MongoDB
db.inventory.insertOne({ item: "notebook", qty: 10 })
db.inventory.updateOne({ item: "notebook" }, { $inc: { qty: 5 } })
db.inventory.find({ item: "notebook" }).toArray()OutputSuccess
Important Notes
You can increment multiple fields at once by listing them inside the $inc object.
Using a negative number with $inc subtracts from the field.
If the field is not a number, $inc will cause an error.
Summary
$inc updates numeric fields by adding or subtracting values.
It creates the field if it does not exist.
Use it to change numbers without replacing the whole document.