In MongoDB, the $divide
aggregation pipeline operator divides one number by another and returns the result.
To use $divide
, pass the numbers in an array. The $divide
operator will divide the first number by the second number. In other words, the first number is the dividend, and the second number is the divisor.
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 }
We can use the $divide
operator within an aggregation pipeline to divide one of those numbers by the other.
db.data.aggregate(
[
{ $project: {
_id: 0,
a: 1,
b: 1,
result: { $divide: [ "$a", "$b" ] } }
}
]
)
Result:
{ "a" : 1000, "b" : 2, "result" : 500 }
If we want to divide b
field by the a
field, we would need to swap them around.
Example:
db.data.aggregate(
[
{ $project: {
_id: 0,
a: 1,
b: 1,
result: { $divide: [ "$b", "$a" ] } }
}
]
)
Result:
{ "a" : 1000, "b" : 2, "result" : 0.002 }
Negative Numbers
Suppose we add the following document to our collection:
{ "_id" : 2, "a" : 1000, "b" : -2 }
This includes a negative number. But that’s not a problem, because a negative number is still a number, and we can certainly divide any number by a negative number.
Example:
db.data.aggregate(
[
{ $project: {
_id: 0,
a: 1,
b: 1,
result: { $divide: [ "$a", "$b" ] } }
}
]
)
Result:
{ "a" : 1000, "b" : 2, "result" : 500 } { "a" : 1000, "b" : -2, "result" : -500 }
Here it is switched around, so that we divide a negative number by a positive number:
db.data.aggregate(
[
{ $project: {
_id: 0,
a: 1,
b: 1,
result: { $divide: [ "$b", "$a" ] } }
}
]
)
Result:
{ "a" : 1000, "b" : 2, "result" : 0.002 } { "a" : 1000, "b" : -2, "result" : -0.002 }
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 divide a field by a fixed amount.
Example:
db.data.aggregate(
[
{ $project: {
_id: 0,
result: { $multiply: [ "$a", 5 ] } }
}
]
)
Result:
{ "result" : 5000 } { "result" : 5000 }