MongoDB $multiply 运算符
MongoDB 中的 $multiply
运算符是什么
MongoDB 提供了各种算术表达式运算符。$multiply
运算符是其中之一。该运算符用于聚合管道阶段中。该运算符用于将两个或多个数字相乘并返回结果。
$multiply
运算符的语法
{ $multiply: [ < expression 1 >, < expression 2 >, ... < expression n > ] }
要使用这个运算符,你需要将参数传递给一个数组。
示例
在以下示例中,我们使用的是:
Database: javaTpoint
Collection: products
Document: Ten documents that contain the details of each product
>db.products.find().pretty()
{
{
"_id" : 1,
"name" : "BlueBox",
"x" : 10,
"y" : 50,
"billYear" : 2018
}
{
"_id" : 2,
"name" : "GreenBox",
"x" : 10,
"y" : 6,
"billYear" : 2017
}
{
"_id" : 3,
"name" : "RedBox",
"x" : 7,
"y" : 9,
"billYear" : 2018
}
{
"_id" : 4,
"name" : "WhiteBox",
"x" : 2,
"y" : 7,
"z" : 4,
"billYear" : 2019
}
{
"_id" : 5,
"name" : "BlueBox",
"x" : 4,
"y" : 12,
"billYear" : 2020
}
{
"_id" : 6,
"name" : "BlueBox",
"x" : 10,
"y" : 5,
"billYear" : 2021
}
{
"_id" : 7,
"name" : "WhiteBox",
"x" : 5,
"y" : 1,
"z" : 45,
"billYear" : 2019
}
{
"_id" : 8,
"name" : "GreenBox",
"x" : -15,
"y" : 5,
"billYear" : 2018
}
{
"_id" : 9,
"name" : "BlackBox",
"billDetail" : {
"x" : 45,
"y" : 56,
}
"billYear" : 2021
}
{
"_id" : 10,
"name" : "WhiteBox",
"x" : 4,
"y" : 5,
"z" : 6,
"billYear" : 2020
}
}
示例1:使用$multiply操作符(用于两个数字)
在这个示例中,我们将会把BlueBox中的”x”和”y”字段相乘。
db.products.aggregate(
[
{match: { name : "BlueBox"}},
{project:
{
name : 1,
x : 1,
y : 1,
answer : {multiply: ["x", "$y"]}
}
}
]
)
输出:
{
"_id" : 1,
"name" : "BlueBox",
"x" : 10,
"y" : 50,
"answer" : 500,
}
{
"_id" : 5,
"name" : "BlueBox",
"x" : 4,
"y" : 12,
"answer" : 48,
}
{
"_id" : 6,
"name" : "BlueBox",
"x" : 10,
"y" : 5,
"answer" : 50,
}
示例2:使用 $multiply 运算符(用于三个数字)
在这个示例中,我们将在WhiteBox中将”x”、”y”和”z”字段进行相乘。
db.products.aggregate(
[
{match: { name : "WhiteBox"}},
{project:
{
name : 1,
x : 1,
y : 1,
z : 1,
answer : {multiply: ["x", "y", "z" ]}
}
}
]
)
输出结果:
{
"_id" : 4,
"name" : "WhiteBox",
"x" : 2,
"y" : 7,
"z" : 4,
"answer" : 56
}
{
"_id" : 7,
"name" : "WhiteBox",
"x" : 5,
"y" : 1,
"z" : 45,
"answer" : 225
}
{
"_id" : 10,
"name" : "WhiteBox",
"x" : 4,
"y" : 5,
"z" : 6,
"answer" : 120
}
示例3:在嵌入文档中使用$multiply运算符
在这个示例中,我们将在BlackBox中将”billDetail.x”和”billDetail.y”字段相乘。
db.products.aggregate(
[
{match: { name : "BlackBox"}},
{project:
{
name : 1,
x : 1,
y : 1,
answer : {multiply: ["billDetail.x", "$billDetail.y"]}
}
}
]
)
输出:
{
"_id" : 9,
"name" : "BlackBox",
"x" : 45,
"y" : 56,
"answer" : 2520
}
示例4:给数组添加一个固定的数字
如果用户想把字段乘以一个特定的数字,用户可以这样做。在这个示例中,我们将把RedBox的”x”字段乘以10。
db.products.aggregate(
[
{match: { name : "RedBox"}},
{project:
{
name : 1,
x : 1,
answer : { multiply : [ "x", 10 ]}
}
}
]
)
输出:
{
"_id" : 3,
"name" : "RedBox",
"x" : 7,
"answer" : 70,
}