Learn how to use divide in MongoDB Aggregate Pipelines. Our MongoDB Support team is here to help you with your questions and concerns.
How to Use divide in MongoDB Aggregate Pipelines
The `$divide` operator in MongoDB lets us easily perform division within an aggregation pipeline. It takes two numbers, divides one by the other, and returns the result.
Today, we will explore how to use `$divide`, including its syntax, examples, and how it handles both positive and negative numbers.
An Overview:
- Syntax of `$divide`
- Example 1: Basic Division
- Example 2: Reversing the Division
- Handling Negative Numbers
- Example 3: Using Fixed Numbers
- Using $divide with Nested Fields
- Error Handling with $divide
Syntax of `$divide`
The basic syntax for using `$divide` within an aggregation is as follows:
{ $divide: [expression1, expression2] }
Here, expression1 is the dividend (the number to be divided). And, expression2 is the divisor (the number by which the dividend is divided).
Both arguments can be any valid expressions, as long as they resolve to numerical values.
Example 1: Basic Division
Suppose we have a MongoDB collection named `data` with the following document:
{ "_id": 1, "a": 1000, "b": 2 }
To divide field `a` by field `b`, we can use `$divide` within an aggregation pipeline:
db.data.aggregate([
{ $project: {
_id: 0,
a: 1,
b: 1,
result: { $divide: [ "$a", "$b" ] }
}}
])
Result: { “a”: 1000, “b”: 2, “result”: 500 }
Here, `a` (1000) is divided by `b` (2), giving the result of 500.
Example 2: Reversing the Division
If we want to divide `b` by `a`, simply swap the fields in the `$divide` expression:
db.data.aggregate([
{ $project: {
_id: 0,
a: 1,
b: 1,
result: { $divide: [ "$b", "$a" ] }
}}
])
Result: { “a”: 1000, “b”: 2, “result”: 0.002 }
In this case, `b` (2) is divided by `a` (1000), resulting in `0.002`.
Handling Negative Numbers
MongoDB’s `$divide` operator can handle negative numbers without issue. For instance, if we add the following document to the `data` collection:
{ "_id": 2, "a": 1000, "b": -2 }
We can still divide `a` by `b`:
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 }
Even though `b` is negative, the `$divide` operator processes the division without any issues. The result is `-500` when `a` (1000) is divided by `b` (-2).
Now, if we switch the operation to divide a negative number by a positive one:
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 }
Here, dividing a negative `b` (-2) by `a` (1000) returns `-0.002`.
Example 3: Using Fixed Numbers
We can also divide a field by a fixed value instead of another field. For example, if we want to multiply the `a` field by a fixed number, such as 5, the query would look like this:
db.data.aggregate([
{ $project: {
_id: 0,
result: { $multiply: [ "$a", 5 ] }
}}
])
Result:
{ “result”: 5000 }
{ “result”: 5000 }
In other words, this operation multiplies the value of `a` (1000) by 5, returning 5000.
Using $divide with Nested Fields
MongoDB documents often contain nested structures, such as subdocuments or arrays, and the $divide operator can be used effectively within these contexts.
For example,
{
"_id": 1,
"sales": {
"total_revenue": 5000,
"total_customers": 100
}
}
In this example, we can divide total_revenue by total_customers to calculate average revenue per customer. Here’s how to achieve that:
db.data.aggregate([
{ $project: {
_id: 0,
revenue_per_customer: { $divide: [ "$sales.total_revenue", "$sales.total_customers" ] }
}}
])
Result: { “revenue_per_customer”: 50 }
This method is useful when working with complex datasets that have nested fields and require mathematical operations to analyze the data.
Error Handling with $divide
While the $divide operator is powerful, certain conditions can lead to errors or unexpected results. For example, dividing by zero or attempting to divide non-numeric values can cause issues in your aggregation pipeline. Here are some common errors:
- MongoDB doesn’t throw an error for division by zero, but it will return null. We can prevent this by adding a conditional check using $cond to avoid division when the divisor is zero.
- If one or both arguments passed to $divide resolve to non-numeric values, MongoDB will also return null. To avoid this, ensure data types are properly handled and convert non-numeric fields using $toDouble or $toInt.
For example: Avoiding Division by Zero
db.data.aggregate([
{ $project: {
_id: 0,
result: {
$cond: {
if: { $eq: [ "$b", 0 ] },
then: "Division by zero",
else: { $divide: [ "$a", "$b" ] }
}
}
}}
])
This example ensures that division by zero is handled, returning a meaningful message rather than null.
[Need assistance with a different issue? Our team is available 24/7.]
Conclusion
The `$divide` operator in MongoDB is a powerful tool for performing division within aggregation pipelines. It can handle both positive and negative numbers and allows you to divide fields by other fields or by fixed values.
In brief, our Support Experts demonstrated how to use divide in MongoDB Aggregate Pipelines.
0 Comments