Front-end Tutorials

Front-end Tutorials

HTMLCSSSassJavaScriptReactJS
CMS Tutorials

CMS Tutorials

WordPress
Tutorials expand

MongoDB Aggregation

MongoDB $divide Operator

Updated on Oct 31, 2024
By Mari Selvan
👁️ 42 - Views
⏳ 4 mins
💬 1 Comment
MongoDB $divide Operator

Photo Credit to CodeToFun

🙋 Introduction

In MongoDB's aggregation framework, the $divide operator serves as a fundamental tool for performing division operations on numerical data. This operator enables users to divide one number by another, facilitating various computations and transformations within aggregation pipelines.

Let's delve into the details of how the $divide operator functions and its applications within MongoDB's aggregation framework.

💡 Syntax

The syntax for the $divide method is straightforward:

syntax.js
Copied
Copy To Clipboard
{ $divide: [ <dividend>, <divisor> ] }
  • $divide: This operator signifies that the subsequent operation will perform a division.
  • <dividend>: This represents the number to be divided.
  • <divisor>: This represents the number by which the dividend will be divided.

📝 Example

⌨️ Input

Consider a collection named sales containing documents with fields revenue and quantity, representing sales information. Here are sample documents from the sales collection:

Input
Copied
Copy To Clipboard
[
  { "_id": ObjectId("609c26812e9274a86871bc6a"), "revenue": 5000, "quantity": 10 },
  { "_id": ObjectId("609c26812e9274a86871bc6b"), "revenue": 7500, "quantity": 15 },
  { "_id": ObjectId("609c26812e9274a86871bc6c"), "revenue": 10000, "quantity": 20 }
]

🔄 Aggregation

Suppose we want to calculate the average revenue per unit sold. Here's how you can achieve this using the $divide operator:

example.js
Copied
Copy To Clipboard
db.sales.aggregate([
  {
    $project: {
      avgRevenuePerUnit: { $divide: ["$revenue", "$quantity"] }
    }
  }
])

🧩 Explanation

  • $project: This stage reshapes documents in the pipeline by including or excluding fields or computing new values.
  • $divide: Performs the division operation, where revenue is the dividend and quantity is the divisor.

When discussing how the above aggregation works:

  • For the first document: avgRevenuePerUnit = revenue / quantity = 5000 / 10 = 500
  • For the second document: avgRevenuePerUnit = revenue / quantity = 7500 / 15 = 500
  • For the third document: avgRevenuePerUnit = revenue / quantity = 10000 / 20 = 500

💻 Output

Now, let's take a look at the output generated by the aggregation pipeline:

Output
Copied
Copy To Clipboard
{ "_id": ObjectId("609c26812e9274a86871bc6a"), "avgRevenuePerUnit": 500 }
{ "_id": ObjectId("609c26812e9274a86871bc6b"), "avgRevenuePerUnit": 500 }
{ "_id": ObjectId("609c26812e9274a86871bc6c"), "avgRevenuePerUnit": 500 }

📚 Use Cases

  1. Performance Metrics:

    The $divide operator is valuable for computing performance metrics such as revenue per unit, cost per unit, or average order value.

  2. Data Transformation:

    Division operations can be used to normalize values or scale data within a dataset.

  3. Financial Analysis:

    When analyzing financial data, calculating ratios or averages often involves division operations facilitated by the $divide operator.

🎉 Conclusion

The $divide operator in MongoDB's aggregation framework provides a powerful mechanism for performing division operations within aggregation pipelines. Whether you're computing performance metrics, transforming data, or conducting financial analysis, mastering the usage of $divide empowers you to efficiently manipulate numerical data and extract meaningful insights from your datasets.

With its intuitive syntax and diverse applications, the $divide operator proves to be a valuable asset for handling numerical data effectively within MongoDB. Incorporate it into your aggregation pipelines to unlock new dimensions of data analysis and gain deeper insights into your datasets.

👨‍💻 Join our Community:

To get interesting news and instant updates on Front-End, Back-End, CMS and other Frameworks. Please Join the Telegram Channel:

Author

author
👋 Hey, I'm Mari Selvan

For over eight years, I worked as a full-stack web developer. Now, I have chosen my profession as a full-time blogger at codetofun.com.

Buy me a coffee to make codetofun.com free for everyone.

Buy me a Coffee

Share Your Findings to All

Subscribe
Notify of
guest
1 Comment
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
We make use of cookies to improve our user experience. By using this website, you agree with our Cookies Policy
AgreeCookie Policy