Database Manual / Reference / Query Language / Expressions

$multiply (aggregation)(聚合)

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 $multiply operation. To improve performance, group references at the end of the argument list. For example,从MongoDB 6.1开始,您可以优化$multiply操作。为了提高性能,请将引用分组到参数列表的末尾。例如,

$multiply: [ 1, 2, 3, '$a', '$b', '$c' ]

Behavior行为

When input types are mixed, $multiply promotes the smaller input type to the larger of the two. A type is considered larger when it represents a wider range of values. The order of numeric types from smallest to largest is: 当输入类型混合时,$multiply会将较小的输入类型升级为两者中较大的输入类型。当一个类型代表更宽的值范围时,它被认为更大。数字类型从最小到最大的顺序是:integer → long → double → decimal

The larger of the input types also determines the result type unless the operation overflows and is beyond the range represented by that larger data type. In cases of overflow, $multiply promotes the result according to the following order:较大的输入类型也决定了结果类型,除非操作溢出并且超出了较大数据类型表示的范围。在溢出的情况下,$multiply会按照以下顺序提升结果:

  • If the larger input type is integer, the result type is promoted to long.如果较大的输入类型是integer,则结果类型将提升为long
  • If the larger input type is long, the result type is promoted to double.如果较大的输入类型是integer,则结果类型将提升为double
  • If the larger type is double or decimal, the overflow result is represented as + or - infinity. There is no type promotion of the result.如果较大的类型是doubledecimal,则溢出结果表示为+或-无穷大。结果没有类型推广。

Example示例

Consider a sales collection with the following documents:考虑一个包含以下文件的sales集合:

db.sales.insertMany( [
{ _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表达式将pricequantity字段相乘:

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 }