Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
MongoDB divide aggregation operator?
The $divide operator in MongoDB performs division between two numbers during aggregation. It takes an array of exactly two numeric expressions and returns the result of dividing the first by the second.
Syntax
{ $divide: [ <expression1>, <expression2> ] }
Sample Data
Let us first create a collection with documents ?
db.aggregationOperatorDemo.insertOne({
"FirstValue": 392883,
"SecondValue": 10000000000
});
{
"acknowledged": true,
"insertedId": ObjectId("5cd541452cba06f46efe9f01")
}
Following is the query to display all documents from the collection ?
db.aggregationOperatorDemo.find().pretty();
{
"_id": ObjectId("5cd541452cba06f46efe9f01"),
"FirstValue": 392883,
"SecondValue": 10000000000
}
Example
Following is the query to use the $divide aggregation operator ?
db.aggregationOperatorDemo.aggregate([
{ "$project": { "Value": { "$divide": ["$FirstValue", "$SecondValue"] } } }
]);
{ "_id": ObjectId("5cd541452cba06f46efe9f01"), "Value": 0.0000392883 }
Key Points
- The
$divideoperator requires exactly two numeric arguments. - Division by zero will result in an error.
- The result is always a floating-point number, even when dividing integers.
Conclusion
The $divide operator provides a simple way to perform division operations in MongoDB aggregation pipelines. Use it within $project stages to calculate ratios, percentages, or any division-based computations on your data.
Advertisements
