$multiply (aggregation)
On this page本页内容
Definition定义
$multiply
-
Multiplies numbers together and returns the result.将数字相乘并返回结果。Pass the arguments to将参数传递给数组中的$multiply
in an array.$multiply
。The$multiply
expression has the following syntax:$multiply
表达式具有以下语法:{ $multiply: [ <expression1>, <expression2>, ... ] }
The arguments can be any valid expression as long as they resolve to numbers.参数可以是任何有效的表达式,只要它们解析为数字即可。For more information on expressions, see Expressions.有关表达式的详细信息,请参阅表达式。Starting in MongoDB 6.1 you can optimize the从MongoDB 6.1开始,您可以优化$multiply
operation. To improve performance, group references at the end of the argument list. For example,$multiply
操作。为了提高性能,请在参数列表的末尾对引用进行分组。例如$multiply: [ 1, 2, 3, '$a', '$b', '$c' ]
Example实例
Consider a 考虑一个包含以下文档的sales
collection with the following documents:sales
集合:
{ "_id" : 1, "item" : "abc", "price" : 10, "quantity": 2, date: ISODate("2014-03-01T08:00:00Z") }
{ "_id" : 2, "item" : "jkl", "price" : 20, "quantity": 1, date: ISODate("2014-03-01T09:00:00Z") }
{ "_id" : 3, "item" : "xyz", "price" : 5, "quantity": 10, date: ISODate("2014-03-15T09:00:00Z") }
The following aggregation uses the 以下聚合使用$multiply
expression in the $project
pipeline to multiply the price
and the quantity
fields:$project
管道中的$multiply
表达式来乘以price
和quantity
字段:
db.sales.aggregate(
[
{ $project: { date: 1, item: 1, total: { $multiply: [ "$price", "$quantity" ] } } }
]
)
The operation returns the following results:该操作返回以下结果:
{ "_id" : 1, "item" : "abc", "date" : ISODate("2014-03-01T08:00:00Z"), "total" : 20 }
{ "_id" : 2, "item" : "jkl", "date" : ISODate("2014-03-01T09:00:00Z"), "total" : 20 }
{ "_id" : 3, "item" : "xyz", "date" : ISODate("2014-03-15T09:00:00Z"), "total" : 50 }