Practical Examples
Real-World Data Grouping Scenarios
MongoDB's grouping capabilities are powerful tools for solving complex data analysis challenges across various domains.
Example 1: E-commerce Sales Analysis
## Group sales by product category and calculate key metrics
db.sales.aggregate([
{
$group: {
_id: "$category",
totalRevenue: { $sum: "$price" },
totalQuantitySold: { $sum: "$quantity" },
averagePrice: { $avg: "$price" },
uniqueProducts: { $addToSet: "$productName" }
}
},
{
$sort: { totalRevenue: -1 }
}
])
Aggregation Pipeline Visualization
graph LR
A[Sales Data] --> B[Group by Category]
B --> C[Calculate Metrics]
C --> D[Sort by Revenue]
D --> E[Final Report]
Example 2: User Activity Tracking
## Analyze user engagement across different time periods
db.userActivity.aggregate([
{
$group: {
_id: {
year: { $year: "$timestamp" },
month: { $month: "$timestamp" }
},
activeUsers: { $addToSet: "$userId" },
totalLogins: { $sum: 1 },
averageSessionDuration: { $avg: "$sessionDuration" }
}
},
{
$project: {
_id: 0,
year: "$_id.year",
month: "$_id.month",
uniqueActiveUsers: { $size: "$activeUsers" },
totalLogins: 1,
averageSessionDuration: 1
}
}
])
Example 3: Inventory Management
## Group inventory by warehouse and product type
db.inventory.aggregate([
{
$group: {
_id: {
warehouse: "$warehouseLocation",
productType: "$category"
},
totalQuantity: { $sum: "$quantity" },
lowStockItems: {
$push: {
$cond: [
{ $lt: ["$quantity", 10] },
"$productName",
"$$REMOVE"
]
}
}
}
}
])
Comparative Analysis Methods
Scenario |
Grouping Strategy |
Key Metrics |
Sales |
By Category |
Total Revenue, Quantity |
User Activity |
By Time Period |
Active Users, Logins |
Inventory |
By Location & Type |
Stock Levels, Low Items |
Advanced Grouping Techniques
Multilevel Grouping
## Complex grouping with multiple levels
db.transactions.aggregate([
{
$group: {
_id: {
region: "$region",
year: { $year: "$date" },
month: { $month: "$date" }
},
totalSales: { $sum: "$amount" },
transactionCount: { $sum: 1 }
}
}
])
- Use selective grouping
- Create appropriate indexes
- Limit result set size
- Use
$match
early in pipeline
LabEx Recommendation
Leverage these practical examples to:
- Develop robust data analysis skills
- Understand complex aggregation techniques
- Solve real-world data challenges
By mastering these practical grouping strategies, you'll transform raw data into meaningful insights with MongoDB and LabEx.