Database Manual / Reference / Query Language / Update / Fields

$inc

Definition定义

$inc
The $inc operator increments a field by a specified value.$inc运算符将字段增加一个指定的值。

Compatibility兼容性

You can use $inc for deployments hosted in the following environments:您可以将$inc用于在以下环境中托管的部署:

  • MongoDB Atlas: The fully managed service for MongoDB deployments in the cloud:云中MongoDB部署的完全托管服务
  • MongoDB Enterprise: The subscription-based, self-managed version of MongoDB:MongoDB的基于订阅的自我管理版本
  • MongoDB Community: The source-available, free-to-use, and self-managed version of MongoDB:MongoDB的源代码可用、免费使用和自我管理版本

Syntax语法

The $inc operator has the following form:$inc运算符具有以下形式:

{ $inc: { <field1>: <amount1>, <field2>: <amount2>, ... } }

To specify a <field> in an embedded document or in an array, use dot notation.要在嵌入式文档或数组中指定<field>,请使用点符号

Behavior行为

Starting in MongoDB 5.0, update operators process document fields with string-based names in lexicographic order. Fields with numeric names are processed in numeric order. See Update Operators Behavior for details.从MongoDB 5.0开始,更新运算符按字典顺序处理具有基于字符串的名称的文档字段。具有数字名称的字段按数字顺序处理。有关详细信息,请参阅更新运算符行为

The $inc operator accepts positive and negative values.$inc运算符接受正值和负值。

If the field does not exist, $inc creates the field and sets the field to the specified value.如果该字段不存在,$inc将创建该字段并将该字段设置为指定值。

Use of the $inc operator on a field with a null value will generate an error.在具有null值的字段上使用$inc运算符将生成错误。

$inc is an atomic operation within a single document.是单个文档中的原子操作。

Starting in MongoDB 5.0, mongod no longer raises an error when you use an update operator like $inc with an empty operand expression ( { } ). 从MongoDB 5.0开始,mongod在使用带有空操作数表达式({ })的更新运算符(如$inc)时不再引发错误。An empty update results in no changes and no oplog entry is created (meaning that the operation is a no-op).空更新不会导致任何更改,也不会创建oplog条目(这意味着该操作是无操作)。

Example示例

Create the products collection:创建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:以下updateOne()操作使用$inc运算符来:

  • increase the "metrics.orders" field by 1"metrics.orders"字段增加1
  • increase the quantity field by -2 (which decreases quantity)quantity字段增加-2(减少quantity
db.products.updateOne(
{ sku: "abc123" },
{ $inc: { quantity: -2, "metrics.orders": 1 } }
)

The updated document would resemble:更新后的文件类似于:

{
_id: 1,
sku: 'abc123',
quantity: 8,
metrics: { orders: 3, ratings: 3.5 }
}