On this page本页内容
$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>
,请使用点表示法。
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, 从MongoDB 5.0开始,当使用带有空操作数表达式(mongod
no longer raises an error when you use an update operator like $inc
with an empty operand expression ( { }
). {}
)的更新运算符(如$inc
)时,mongod
不再引发错误。An empty update results in no changes and no oplog entry is created (meaning that the operation is a no-op).空更新不会导致任何更改,也不会创建oplog条目(这意味着该操作是无操作)。
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
运算符:
"metrics.orders"
field by 1"metrics.orders"
字段增加1quantity
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 } }