0
0
MongodbConceptBeginner · 3 min read

What is Aggregation in MongoDB: Explanation and Examples

In MongoDB, aggregation is a way to process and transform data from multiple documents into summarized results. It uses a pipeline of stages like $match and $group to filter, group, and calculate values from collections.
⚙️

How It Works

Aggregation in MongoDB works like a factory assembly line where data flows through several steps, each transforming it in some way. Imagine you have a big box of mixed fruits and you want to sort, count, and sum their weights. Aggregation lets you do this by passing the data through stages that filter, group, and calculate.

Each stage in the aggregation pipeline takes the input documents, processes them, and passes the output to the next stage. This lets you build complex queries that summarize data, such as totals, averages, or counts, all in one operation.

💻

Example

This example shows how to use aggregation to find the total sales per product from a sales collection.

mongodb
db.sales.aggregate([
  { $group: { _id: "$product", totalSales: { $sum: "$amount" } } }
])
Output
[ { "_id": "apple", "totalSales": 150 }, { "_id": "banana", "totalSales": 200 } ]
🎯

When to Use

Use aggregation when you need to analyze or summarize data across many documents. It is perfect for reports, statistics, and data transformations like calculating averages, totals, or grouping by categories.

For example, an online store can use aggregation to find total sales per product, average order value, or count customers by region.

Key Points

  • Aggregation processes data through a pipeline of stages.
  • Each stage transforms or filters the data.
  • Common stages include $match, $group, and $sort.
  • Aggregation is used for data summarization and analysis.

Key Takeaways

Aggregation in MongoDB summarizes and transforms data using a pipeline of stages.
It is useful for calculating totals, averages, counts, and grouping data.
Aggregation pipelines process documents step-by-step for complex queries.
Use aggregation for reports, analytics, and data processing tasks.