Aggregatios

Aggregations

๐Ÿ”น What is Aggregation?


Aggregation means processing data to get computed results.

Similar to SQL operations like:

  • GROUP BY
  • COUNT
  • SUM
  • AVG

 Example:

  • Total sales
  • Average age
  • Count of users


๐Ÿ”น Aggregation Framework

MongoDB provides an Aggregation Framework, which works like a pipeline.

Data flows through multiple stages, and each stage transforms it.


๐Ÿ”น Aggregation Pipeline Concept

Think like this:

Input data โ†’ Stage 1 โ†’ Stage 2 โ†’ Stage 3 โ†’ Output

Each stage performs a specific operation


๐Ÿ”น Basic Syntax

db.collection.aggregate([

{ stage1 },

{ stage2 }

])



๐Ÿ”น Important Stages


1. $match

Filters data (like WHERE)

Example:

db.users.aggregate([ { $match: { age: { $gt: 25 } } } ])



2. $group

Groups data (like GROUP BY)

Example:

db.users.aggregate([

{ $group: { _id: "$age", count: { $sum: 1 } } }

])

Groups users by age and counts them



3. $project


Selects specific fields

Example:

db.users.aggregate([

{ $project: { name: 1, age: 1 } }

])


4. $sort


Sort results

db.users.aggregate([ { $sort: { age: 1 } } ])


5. $limit

Limit results


db.users.aggregate([ { $limit: 5 } ])


6. $skip


Skip documents

db.users.aggregate([ { $skip: 5 } ])


7. $lookup


Join collections (like SQL JOIN)

Used to combine data from different collections

๐Ÿ”น Example Pipeline

db.orders.aggregate([

{ $match: { status: "completed" } },

{ $group: { _id: "$customerId", total: { $sum: "$amount" } } },

{ $sort: { total: -1 } }

])


Steps:

  1. Filter completed orders
  2. Group by customer
  3. Calculate total amount
  4. Sort descending


Why Aggregation is Powerful

  • Handles complex data processing
  • Reduces need for multiple queries
  • Works efficiently on large data


Simple Understanding

  • Aggregation = data processing
  • Pipeline = step-by-step transformation
  • Stages = operations like filter, group, sort