In MongoDB, the $multiply
aggregation pipeline operator multiplies numbers together and returns the result.
To use the $multiply
operator, pass the numbers to the operator in an array.
The arguments can be any valid expression, as long as they resolve to numbers.
Example
Suppose we have a collection called data
with the following document:
{ "_id" : 1, "a" : 1000, "b" : 2, "c" : 3 }
We can use the $multiply
operator within an aggregation pipeline to multiply two or more of those numbers together.
Multiply 2 Numbers
Here’s an example of multiplying two numbers together.
db.data.aggregate(
[
{ $project: {
_id: 0,
a: 1,
b: 1,
result: { $multiply: [ "$a", "$b" ] } }
}
]
)
Result:
{ "a" : 1000, "b" : 2, "result" : 2000 }
Multiply 3 Numbers
Here it is again, except this time we multiply all three numbers together.
db.data.aggregate(
[
{ $project: {
_id: 0,
a: 1,
b: 1,
c: 1,
result: { $multiply: [ "$a", "$b", "$c" ] } }
}
]
)
Result:
{ "a" : 1000, "b" : 2, "c" : 3, "result" : 6000 }
Negative Values
The numbers can be positive or negative.
Suppose we add the following document to our collection:
{ "_id" : 2, "a" : 1000, "b" : -2, "c" : -3 }
Now let’s run the previous examples again and see what happens:
db.data.aggregate(
[
{ $project: {
_id: 0,
a: 1,
b: 1,
result: { $multiply: [ "$a", "$b" ] } }
}
]
)
Result:
{ "a" : 1000, "b" : 2, "result" : 2000 } { "a" : 1000, "b" : -2, "result" : -2000 }
And here it is with three numbers:
db.data.aggregate(
[
{ $project: {
_id: 0,
a: 1,
b: 1,
c: 1,
result: { $multiply: [ "$a", "$b", "$c" ] } }
}
]
)
Result:
{ "a" : 1000, "b" : 2, "c" : 3, "result" : 6000 } { "a" : 1000, "b" : -2, "c" : -3, "result" : 6000 }
When you multiply a negative number by a positive number then the product is always negative. But when you multiply two negative numbers or two positive numbers, the product is always positive.
Add Your Own Number
You aren’t necessarily restricted to just the numbers in the document/s. You can use your own numbers if you need to multiply all fields by a fixed amount.
Example:
db.data.aggregate(
[
{ $project: {
_id: 0,
result: { $multiply: [ "$a", "$b", "$c", 2.5 ] } }
}
]
)
Result:
{ "result" : 15000 } { "result" : 15000 }