$inc

On this page本页内容

Definition定义

$inc

The $inc operator increments a field by a specified value and 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. 从MongoDB 5.0开始,更新运算符以词典顺序处理具有基于字符串的名称的文档字段。Fields with numeric names are processed in numeric order. 具有数字名称的字段按数字顺序处理。See Update Operators Behavior for details.有关详细信息,请参阅更新运算符行为

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开始,当使用带有空操作数表达式({})的更新运算符(如$inc)时,mongod不再引发错误。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(减少数量)
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 }
}
←  $currentDate$min →