Practical Examples
E-commerce Sales Analysis
db.sales.aggregate([
{ $match: {
date: {
$gte: ISODate("2023-01-01"),
$lt: ISODate("2024-01-01")
}
}},
{ $group: {
_id: {
month: { $month: "$date" },
product: "$productCategory"
},
totalRevenue: { $sum: "$amount" },
totalOrders: { $sum: 1 }
}},
{ $sort: { totalRevenue: -1 }}
])
Analysis Workflow
graph LR
A[Raw Sales Data] --> B[Filter by Date]
B --> C[Group by Month/Category]
C --> D[Calculate Revenue]
D --> E[Sort Results]
Customer Segmentation
Customer Metrics Calculation
db.customers.aggregate([
{ $project: {
age: 1,
totalSpend: { $sum: "$purchases.amount" },
purchaseFrequency: { $size: "$purchases" }
}},
{ $bucket: {
groupBy: "$totalSpend",
boundaries: [0, 500, 1000, 2000, 5000],
default: "High Spender",
output: {
"customerCount": { $sum: 1 },
"averageAge": { $avg: "$age" }
}
}}
])
Inventory Management
Stock Level Analysis
db.inventory.aggregate([
{ $group: {
_id: "$category",
totalQuantity: { $sum: "$quantity" },
lowStockItems: {
$push: {
$cond: [
{ $lt: ["$quantity", 10] },
"$productName",
"$$REMOVE"
]
}
}
}},
{ $project: {
category: "$_id",
totalQuantity: 1,
lowStockCount: { $size: "$lowStockItems" },
criticalProducts: "$lowStockItems"
}}
])
User Activity Dashboard
db.userActivity.aggregate([
{ $unwind: "$sessions" },
{ $group: {
_id: "$userId",
totalSessionTime: { $sum: "$sessions.duration" },
averageSessionLength: { $avg: "$sessions.duration" },
loginCount: { $sum: 1 }
}},
{ $match: {
totalSessionTime: { $gt: 3600 }
}},
{ $sort: { loginCount: -1 }}
])
Aggregation Complexity Levels
Complexity |
Characteristics |
Use Case |
Basic |
Simple filtering/grouping |
Quick insights |
Intermediate |
Multiple transformations |
Detailed reporting |
Advanced |
Complex calculations |
Deep data analysis |
LabEx Practical Recommendations
- Start with simple aggregation pipelines
- Gradually increase complexity
- Use
explain()
to understand query performance
- Break complex queries into smaller stages
- Test and validate results at each stage
Real-world Application Scenarios
- Financial reporting
- User behavior analysis
- Inventory management
- Performance tracking
- Predictive analytics
By mastering these practical examples, you'll develop robust data analysis skills using MongoDB aggregation in your LabEx projects and professional development.