Docs Menu

$multiply (aggregation)

項目一覧

$multiply

Multiplies numbers together and returns the result. Pass the arguments to $multiply in an array.

$multiply式の構文は次のとおりです。

{ $multiply: [ <expression1>, <expression2>, ... ] }

引数は、数値に変換される限り、どのような有効なでもかまいません。式の詳細については、「式演算子」を参照してください。

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,

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

入力型が混在している場合、$multiply は小さい入力型を 2 つのうち大きい方に昇格させます。型が大きいとみなされるのは、より広い範囲の値を表す場合です。数値型の最小値から最大値の順は、integer → long → double → decimal です。

演算がオーバーフローして、大きい方のデータ型で表される範囲を超えない限り、大きい方の入力型によって結果型も決まります。オーバーフローの場合、$multiply は以下の順序に従って結果を昇格させます。

  • より大きな入力型が integer の場合、結果型は long に昇格します。

  • より大きな入力型が long の場合、結果型は double に昇格します。

  • 大きい方の型が double または decimal の場合、オーバーフロー結果は正または負の無限大として表されます。結果型の昇格は行われません。

以下のドキュメントを持つ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:

db.sales.aggregate(
[
{ $project: { date: 1, item: 1, total: { $multiply: [ "$price", "$quantity" ] } } }
]
)

この操作は次の結果を返します。

{ "_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 }

項目一覧