- Reference >
- Operators >
- Update Operators >
- Field Update Operators >
- $inc
$inc¶
-
$inc¶ The
$incoperator increments a value of a field by a specified amount. If the field does not exist,$incadds the field and sets the field to the specified amount.$incaccepts positive and negative incremental amounts. Consider the following syntax:The following example increments the value of
quantityby5for the first matching document in theproductscollection whereskuequalsabc123:To update all matching documents in the collection, specify
multi:trueoption in theupdate()method. For example:The
update()operation increments the value of theagefield by1for all documents in therecordscollection that have anagefield equal to20.The
$incoperator can operate on multiple fields in a document. The followingupdate()operation uses the$incoperator to modify both thequantityfield and thesalesfield for the first matching document in theproductscollection whereskuequalsabc123:In the above example, the
$incoperator expression specifies-2for thequantityfield to decrease the value of thequantityfield (i.e. increment by-2) and specifies2for thesalesfield to increase the value of thesalesfield by2.