On this page
$mul
在本页面
Definition
$mul
- 2.6 版的新功能。
将字段的值乘以数字。要指定$mul表达式,请使用以下原型:
{ $mul: { <field1>: <number1>, ... } }
要更新的字段必须包含一个数字值。
要在嵌入式文档或数组中指定<field>
,请使用dot notation。
Behavior
Missing Field
如果文档中不存在该字段,则$mul将创建该字段并将其值设置为与乘法器相同的数字类型的零。
Atomic
$mul是单个文档中的原子操作。
Mixed Type
与混合数字类型(32 位整数,64 位整数,浮点数)的值相乘可能会导致数字类型转换。对于与混合数值类型的值相乘,将应用以下类型转换规则:
32-bit Integer | 64-bit Integer | Float | |
---|---|---|---|
32-bit Integer | 32 位或 64 位整数 | 64-bit Integer | Float |
64-bit Integer | 64-bit Integer | 64-bit Integer | Float |
Float | Float | Float | Float |
Note
如果两个 32 位整数的乘积超过了 32 位整数的最大值,则结果为 64 位整数。
超出 64 位整数最大值的任何类型的整数运算都会产生错误。
Examples
乘以一个字段的值
考虑包含以下文档的集合products
:
{ "_id" : 1, "item" : "ABC", "price" : NumberDecimal("10.99"), "qty" : 25 }
以下db.collection.update()操作使用$mul运算符将price
乘以1.25
并将qty
字段乘以2
来更新文档:
db.products.update(
{ _id: 1 },
{ $mul: { price: NumberDecimal("1.25"), qty: 2 } }
)
该操作产生以下文档,其中新值price
反映原始值10.99
乘以1.25
,新值qty
反映原始值25
乘以2
:
{ "_id" : 1, "item" : "ABC", "price" : NumberDecimal("13.7375"), "qty" : 50 }
将$ mul 运算符应用于不存在的字段
考虑包含以下文档的集合products
:
{ _id: 2, item: "Unknown" }
以下db.collection.update()操作会更新文档,并将$mul运算符应用于文档中不存在的字段price
:
db.products.update(
{ _id: 2 },
{ $mul: { price: NumberLong(100) } }
)
该操作导致以下文档的price
字段设置为数值类型NumberLong的值 0,该类型与乘数相同:
{ "_id" : 2, "item" : "Unknown", "price" : NumberLong(0) }
乘以混合数值类型
考虑包含以下文档的集合products
:
{ _id: 3, item: "XYZ", price: NumberLong(10) }
以下db.collection.update()操作使用$mul运算符将price
字段NumberLong(10)中的值乘以NumberInt(5):
db.products.update(
{ _id: 3 },
{ $mul: { price: NumberInt(5) } }
)
该操作产生以下文档:
{ "_id" : 3, "item" : "XYZ", "price" : NumberLong(50) }
price
字段中的值是NumberLong类型。有关详情,请参见乘法类型转换规则。