$inc
Increments the value of a field by a specified amount, creating the field if it doesn't exist, accepting positive and negative values.
Syntax
{ $inc: { <field1>: <amount1>, <field2>: <amount2> } }
Parameters
field
stringrequiredThe name of the field to increment
amount
numberrequiredThe increment value (positive for increment, negative for decrement)
Examples
Increment staff count
Increase full-time staff count by 3
Query:
db.stores.updateOne({ "_id": "store-001" }, { $inc: { "staff.totalStaff.fullTime": 3 } })
Output:
Increases fullTime staff count by 3
Multiple field increments
Decrease part-time staff by 2 and increase total sales by 5000
Query:
db.stores.updateOne({ "_id": "store-001" }, { $inc: { "staff.totalStaff.partTime": -2, "sales.totalSales": 5000 } })
Output:
Updates multiple numeric fields with different increment values
Create new fields
Create new numeric fields with initial values using increment
Query:
db.stores.updateOne({ "_id": "store-001" }, { $inc: { "staff.contractorCount": 5, "sales.monthlyTarget": 200000 } })
Output:
Creates new fields with specified initial values
Increment array element
Update specific sales figures within array using positional operators
Query:
db.stores.updateOne({ "_id": "store-001", "sales.salesByCategory.categoryName": "Electronics" }, { $inc: { "sales.salesByCategory.$.totalSales": 500 } })
Output:
Increments totalSales for the matching array element by 500