$mul
定义
行为
从MongoDB 5.0开始,当您使用类似于 $mul
的更新运算符与空的操作数表达式( { }
)一起使用时,mongod
将不再引发错误。空更新将不会产生任何变化,也不会创建任何 操作日志 条目(意味着该操作是无效操作)。
从MongoDB 5.0开始,更新运算符按照基于字符串的名称的字典顺序处理文档字段。具有数字名称的字段按照数字顺序处理。有关详细信息,请参阅更新运算符行为。
缺少字段
如果字段在文档中不存在,$mul
将创建该字段,并将值设置为与乘数相同数值类型的零。
原子操作
$mul
是单个文档内的原子操作。
混合类型
使用混合数值类型(32位整数、64位整数、浮点数)的值进行乘法运算可能会导致数值类型转换。对于使用混合数值类型进行乘法运算,以下类型转换规则适用:
32位整数 | 64位整数 | 浮点数 | |
---|---|---|---|
32位整数 | 32位或64位整数 | 64位整数 | 浮点数 |
64位整数 | 64位整数 | 64位整数 | 浮点数 |
浮点数 | 浮点数 | 浮点数 | 浮点数 |
注意
如果两个32位整数的乘积超过了32位整数的最大值,则结果为64位整数。
任何类型的整数运算,如果超过64位整数的最大值,将产生错误。
示例
乘以字段的值
创建products
集合
db.products.insertOne( { "_id" : 1, "item" : "Hats", "price" : Decimal128("10.99"), "quantity" : 25 } )
在以下操作中,db.collection.updateOne()
更新文档。操作符$mul
将price
字段乘以1.25,将quantity
字段乘以2
db.products.updateOne( { _id: 1 }, { $mul: { price: Decimal128( "1.25" ), quantity: 2 } } )
更新后的文档中
price
是原始值10.99乘以1.25quantity
是原始值25乘以2
{ _id: 1, item: 'Hats', price: Decimal128("13.7375"), quantity: 50 }
将 $mul
运算符应用于不存在的字段
将以下文档添加到 products
集合
db.products.insertOne( { _id: 2, item: "Unknown" } )
在以下操作中,db.collection.updateOne()
尝试将 $mul
运算符应用于文档中不存在的字段
db.products.updateOne( { _id: 2 }, { $mul: { price: Decimal128("100") } } )
插入
price
字段设置为 Decimal128("0")
{ "_id" : 2, "item" : "Unknown", "price" : NumberLong(0) }
price
字段与乘数具有相同的类型,Decimal128。
混合数值类型相乘
将以下文档添加到 products
集合
db.products.insertOne( { _id: 3, item: "Scarf", price: Decimal128("10") } )
在以下操作中,db.collection.updateOne()
使用 $mul
运算符将 price
字段中的值(Decimal128(10))与 Decimal128(10) 相乘
db.products.updateOne( { _id: 3 }, { $mul: { price: Int32(5) } } )
操作结果如下文档
{ _id: 3, item: 'Scarf', price: Decimal128("50") }
price
字段中的值为 Decimal128 类型。有关详细信息,请参阅 乘法类型转换规则。