$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.有关表达式的详细信息,请参阅表达式

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表达式将价格和数量字段相乘:

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 }