本文将会介绍如何使用 MongoDB $mul 操作符将字段的值乘以一个倍数。
$mul 是一个字段更新操作符,可以将指定字段的值乘以一个倍数。
$mul 操作符的语法如下:
{ $mul: { <field1>: <number1>, <field2>: <number2>, ... } }
被更新的字段必须是一个数字字段。如果需要更新嵌入式文档中的字段或者数组中的元素,可以使用点符号,例如
如果被更新的字段不存在,$mul 操作符将会创建字段并将其值设置为 0。
接下来的示例我们将会使用一下集合:
db.products.insertMany([
{ "_id" : 1, "name" : "xPhone", "price" : 799, "releaseDate": ISODate("2011-05-14"), "spec" : { "ram" : 4, "screen" : 6.5, "cpu" : 2.66 },"color":["white","black"],"storage":[64,128,256]},
{ "_id" : 2, "name" : "xTablet", "price" : 899, "releaseDate": ISODate("2011-09-01") , "spec" : { "ram" : 16, "screen" : 9.5, "cpu" : 3.66 },"color":["white","black","purple"],"storage":[128,256,512]},
{ "_id" : 3, "name" : "SmartTablet", "price" : 899, "releaseDate": ISODate("2015-01-14"), "spec" : { "ram" : 12, "screen" : 9.7, "cpu" : 3.66 },"color":["blue"],"storage":[16,64,128]},
{ "_id" : 4, "name" : "SmartPad", "price" : 699, "releaseDate": ISODate("2020-05-14"),"spec" : { "ram" : 8, "screen" : 9.7, "cpu" : 1.66 },"color":["white","orange","gold","gray"],"storage":[128,256,1024]},
{ "_id" : 5, "name" : "SmartPhone", "price" : 599,"releaseDate": ISODate("2022-09-14"), "spec" : { "ram" : 4, "screen" : 5.7, "cpu" : 1.66 },"color":["white","orange","gold","gray"],"storage":[128,256]}
])
以下示例使用 $mul 操作符将文档(_id: 5)的price 字段的值增加 10%:
db.products.updateOne({ _id: 5 }, { $mul: { price: 1.1 } })
返回结果显示查询匹配并更新了一个文档:
{
acknowledged: true,
insertedId: null,
matchedCount: 1,
modifiedCount: 1,
upsertedCount: 0
}
以下查询验证了更新后的结果:
db.products.find({
_id: 5
}, {
name: 1,
price: 1
})
[ { _id: 5, name: 'SmartPhone', price: 658.9000000000001 } ]
以下查询使用 $mul 操作符将文档(_id: 1)中数组 storage 的第一个、第二个以及第三个元素的值增加一倍:
db.products.updateOne({
_id: 1
}, {
$mul: {
"storage.0": 2,
"storage.1": 2,
"storage.2": 2
}
})
查询返回结果如下:
{
acknowledged: true,
insertedId: null,
matchedCount: 1,
modifiedCount: 1,
upsertedCount: 0
}
以下查询验证了更新之后的文档内容:
db.products.findOne({ _id: 1 }, { name: 1, storage: 1 })
{ _id: 1, name: 'xPhone', storage: [ 128, 256, 512 ] }
以下示例使用 $mul 操作符将 products 集合中全部文档的 spec 中的 ram 字段值增加一倍:
db.products.updateMany({}, {
$mul: {
"spec.ram": 2
}
})
查询返回结果如下:
{
acknowledged: true,
insertedId: null,
matchedCount: 5,
modifiedCount: 5,
upsertedCount: 0
}
以下查询返回了 products 集合中的全部文档:
db.products.find({}, { name: 1, "spec.ram": 1 })
[
{ _id: 1, name: 'xPhone', spec: { ram: 8 } },
{ _id: 2, name: 'xTablet', spec: { ram: 32 } },
{ _id: 3, name: 'SmartTablet', spec: { ram: 24 } },
{ _id: 4, name: 'SmartPad', spec: { ram: 16 } },
{ _id: 5, name: 'SmartPhone', spec: { ram: 8 } }
]