定义
$incThe
$incoperator increments a field by a specified value.
兼容性
可以使用 $inc 查找托管在以下环境中的部署:
- MongoDB Atlas:用于云中 MongoDB 部署的完全托管服务
MongoDB Enterprise:基于订阅、自我管理的 MongoDB 版本
MongoDB Community:源代码可用、免费使用且可自行管理的 MongoDB 版本
语法
The $inc operator has the following form:
{ $inc: { <field1>: <amount1>, <field2>: <amount2>, ... } }
要在嵌入式文档或数组中指定 <field>,请使用点符号。
行为
从 MongoDB 5.0 开始,更新操作符按字典顺序处理具有基于字符串的名称的文档字段。具有数字名称的字段按数字顺序处理。详情请参阅更新操作符行为。
The $inc operator accepts positive and negative values.
If the field does not exist, $inc creates the field and sets the field to the specified value.
Using the $inc operator on a field with a null value generates an error.
$inc 是单个文档中的原子操作。
Starting in MongoDB 5.0, mongod no longer raises an error when you use an update operator like $inc with an empty operand expression ( { } ). An empty update results in no changes and no oplog entry is created (meaning that the operation is a no-op).
例子
创建 products 集合:
db.products.insertOne( { _id: 1, sku: "abc123", quantity: 10, metrics: { orders: 2, ratings: 3.5 } } )
The following updateOne() operation uses the $inc operator to:
将
"metrics.orders"字段增加 1将
quantity字段减少 2(减少quantity)。
db.products.updateOne( { sku: "abc123" }, { $inc: { quantity: -2, "metrics.orders": 1 } } )
操作返回以下结果:
{ _id: 1, sku: 'abc123', quantity: 8, metrics: { orders: 3, ratings: 3.5 } }