Careeroza
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 }
])
๐น 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 them3. $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 } }
])
๐น Example Pipeline
db.orders.aggregate([
{ $match: { status: "completed" } },
{ $group: { _id: "$customerId", total: { $sum: "$amount" } } },
{ $sort: { total: -1 } }
])Steps:
- Filter completed orders
- Group by customer
- Calculate total amount
- 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