Practical Grouping Examples
Real-World Grouping Scenarios
MongoDB grouping techniques can solve complex data analysis challenges across various domains.
1. E-Commerce Sales Analysis
graph LR
A[Sales Data] --> B[Group by Category]
B --> C[Calculate Total Revenue]
C --> D[Analyze Performance]
Example Code
db.orders.aggregate([
{
$group: {
_id: "$category",
totalRevenue: { $sum: "$price" },
orderCount: { $sum: 1 },
avgOrderValue: { $avg: "$price" }
}
},
{
$sort: { totalRevenue: -1 }
}
])
2. User Activity Tracking
Metric |
Description |
Grouping Method |
Daily Active Users |
Count unique users |
$addToSet |
User Engagement |
Track interaction frequency |
$sum |
User Segmentation |
Group by attributes |
$group |
Example Implementation
db.userActivity.aggregate([
{
$group: {
_id: {
date: { $dateToString: { format: "%Y-%m-%d", date: "$timestamp" } },
platform: "$platform"
},
activeUsers: { $addToSet: "$userId" },
totalSessions: { $sum: 1 }
}
}
])
3. Financial Transaction Analysis
Multi-Stage Aggregation
db.transactions.aggregate([
{
$match: {
timestamp: {
$gte: ISODate("2023-01-01"),
$lt: ISODate("2024-01-01")
}
}
},
{
$group: {
_id: {
month: { $month: "$timestamp" },
type: "$transactionType"
},
totalAmount: { $sum: "$amount" },
transactionCount: { $sum: 1 }
}
},
{
$project: {
month: "$_id.month",
transactionType: "$_id.type",
totalAmount: 1,
transactionCount: 1
}
}
])
4. Inventory Management
graph TD
A[Inventory Data] --> B[Group by Product]
B --> C[Calculate Stock Levels]
C --> D[Identify Low Stock Items]
Stock Level Tracking
db.inventory.aggregate([
{
$group: {
_id: "$productCategory",
totalQuantity: { $sum: "$quantity" },
uniqueProducts: { $addToSet: "$productName" },
lowStockItems: {
$push: {
name: "$productName",
quantity: "$quantity"
}
}
}
},
{
$match: { totalQuantity: { $lt: 100 } }
}
])
Best Practices with LabEx
- Use appropriate indexes
- Optimize aggregation pipeline
- Break complex queries into stages
- Monitor query performance
By exploring these practical grouping examples, you'll develop advanced data analysis skills using MongoDB's powerful aggregation framework with LabEx's comprehensive tutorials.