Practical Aggregation Examples
E-commerce Sales Analysis
Total Revenue by Product Category
db.sales.aggregate([
{ $group: {
_id: "$category",
totalRevenue: { $sum: "$price" },
totalQuantity: { $sum: "$quantity" }
}},
{ $sort: { totalRevenue: -1 } }
])
graph LR
A[Sales Data] --> B[Group by Category]
B --> C[Calculate Revenue]
C --> D[Sort Results]
Financial Transaction Reporting
Monthly Transaction Summary
db.transactions.aggregate([
{ $group: {
_id: {
year: { $year: "$date" },
month: { $month: "$date" }
},
totalIncome: { $sum: { $cond: [{ $gte: ["$amount", 0] }, "$amount", 0] } },
totalExpenses: { $sum: { $cond: [{ $lt: ["$amount", 0] }, { $abs: "$amount" }, 0] } }
}}
])
Inventory Management
Stock Valuation Across Departments
db.inventory.aggregate([
{ $group: {
_id: "$department",
totalStockValue: { $sum: { $multiply: ["$quantity", "$unitPrice"] } },
averageUnitPrice: { $avg: "$unitPrice" }
}}
])
User Activity Analysis
Metric |
Aggregation Technique |
Total Logins |
$sum of login count |
Average Session Duration |
$avg of session time |
Active Users |
$count with conditions |
Complex Aggregation Scenario
db.orders.aggregate([
{ $match: { status: "completed" } },
{ $group: {
_id: "$productId",
totalSales: { $sum: "$price" },
orderCount: { $sum: 1 }
}},
{ $lookup: {
from: "products",
localField: "_id",
foreignField: "_id",
as: "productDetails"
}},
{ $unwind: "$productDetails" },
{ $project: {
productName: "$productDetails.name",
totalSales: 1,
orderCount: 1,
averageOrderValue: { $divide: ["$totalSales", "$orderCount"] }
}},
{ $sort: { totalSales: -1 } }
])
Best Practices for LabEx Developers
- Break complex aggregations into multiple stages
- Use indexes to optimize performance
- Test aggregation pipelines with sample data
- Monitor query execution time
Error Handling and Validation
db.transactions.aggregate([
{ $group: {
_id: null,
safeTotal: {
$sum: {
$ifNull: ["$amount", 0]
}
}
}}
])
Conclusion
These practical examples demonstrate the versatility of MongoDB aggregation, showcasing how complex data analysis can be performed efficiently and precisely.