$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

fieldstringrequired

The name of the field to increment

amountnumberrequired

The 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

Bulk increment operations

Increment values across multiple documents

Query:

db.stores.updateMany({ "city": "Seattle" }, { $inc: { "sales.totalSales": 1000 } })

Output:

Increases totalSales by 1000 for all stores in Seattle

Related