Practical Group Examples
Real-World Aggregation Scenarios
1. E-commerce Sales Analysis
## Group sales by product category
db.orders.aggregate([
{ $group: {
_id: "$category",
totalRevenue: { $sum: "$price" },
orderCount: { $count: {} },
averageOrderValue: { $avg: "$price" }
}}
])
2. User Activity Tracking
## Analyze user login activity by month
db.userLogs.aggregate([
{ $group: {
_id: {
year: { $year: "$loginTime" },
month: { $month: "$loginTime" }
},
uniqueUsers: { $addToSet: "$userId" },
totalLogins: { $count: {} }
}}
])
Advanced Grouping Techniques
Hierarchical Grouping
graph TD
A[Grouping Strategy] --> B[Single Level]
A --> C[Multi-Level Grouping]
A --> D[Nested Grouping]
Complex Multi-Dimensional Grouping
## Group by multiple dimensions
db.sales.aggregate([
{ $group: {
_id: {
region: "$region",
productType: "$product",
quarter: { $quarter: "$saleDate" }
},
totalSales: { $sum: "$amount" },
highestSale: { $max: "$amount" },
lowestSale: { $min: "$amount" }
}}
])
Filtering Before Grouping
Technique |
Description |
Benefit |
$match First |
Filter documents before grouping |
Reduces processing load |
Indexing |
Create indexes on grouping fields |
Improves query speed |
Example of Optimized Grouping
## Efficient grouping with pre-filtering
db.transactions.aggregate([
{ $match: {
status: "completed",
date: { $gte: ISODate("2023-01-01") }
}},
{ $group: {
_id: "$accountType",
totalTransactions: { $count: {} },
totalAmount: { $sum: "$amount" }
}}
])
Specialized Grouping Operations
Accumulator Variations
## Using advanced accumulators
db.inventory.aggregate([
{ $group: {
_id: "$warehouse",
productList: { $push: "$productName" },
uniqueProducts: { $addToSet: "$productName" }
}}
])
LabEx Learning Tip
Explore these practical examples in LabEx's MongoDB simulation environments to gain hands-on experience with real-world aggregation techniques.
Key Takeaways
- Grouping can solve complex data analysis challenges
- Combine multiple accumulators for comprehensive insights
- Pre-filtering improves aggregation performance
- Flexible grouping supports various business intelligence needs