Practical Use Cases
Real-World Scenarios for Field Operators
1. E-commerce Sales Analysis
db.orders.aggregate([
{
$group: {
_id: "$category",
totalRevenue: { $sum: "$totalPrice" },
averageOrderValue: { $avg: "$totalPrice" },
orderCount: { $sum: 1 }
}
},
{
$project: {
category: "$_id",
totalRevenue: { $round: ["$totalRevenue", 2] },
averageOrderValue: { $round: ["$averageOrderValue", 2] },
orderCount: 1
}
},
{ $sort: { totalRevenue: -1 } }
]);
Use Case Scenarios
Scenario |
Field Operators |
Key Benefits |
Sales Reporting |
$group, $sum |
Aggregate sales data |
Customer Segmentation |
$bucket, $project |
Categorize customers |
Inventory Management |
$match, $lookup |
Track product details |
Performance Analytics |
$addFields, $avg |
Calculate metrics |
2. User Engagement Tracking
db.userActivity.aggregate([
{ $match: { timestamp: { $gte: new Date("2023-01-01") } } },
{
$group: {
_id: "$userId",
totalSessions: { $sum: 1 },
averageSessionDuration: { $avg: "$sessionDuration" }
}
},
{
$project: {
userId: "$_id",
engagement: {
$cond: [{ $gte: ["$averageSessionDuration", 300] }, "High", "Low"]
},
totalSessions: 1,
averageSessionDuration: 1
}
}
]);
graph LR
A[Raw Data] --> B[Filter]
B --> C[Group]
C --> D[Transform]
D --> E[Analyze Results]
3. Financial Reporting
db.transactions.aggregate([
{
$match: {
date: {
$gte: new Date("2023-01-01"),
$lt: new Date("2024-01-01")
}
}
},
{
$group: {
_id: {
month: { $month: "$date" },
year: { $year: "$date" }
},
totalIncome: { $sum: "$income" },
totalExpenses: { $sum: "$expenses" }
}
},
{
$project: {
period: {
$concat: [{ $toString: "$_id.month" }, "-", { $toString: "$_id.year" }]
},
netProfit: { $subtract: ["$totalIncome", "$totalExpenses"] }
}
}
]);
LabEx Optimization Strategies
- Use indexes effectively
- Limit document processing
- Break complex aggregations into stages
- Monitor query performance
Key Takeaways
- Field operators enable complex data transformations
- Aggregation pipelines support sophisticated analysis
- Choose operators based on specific use cases
- Always consider performance implications
By leveraging these practical use cases, developers can unlock powerful data processing capabilities in MongoDB, transforming raw data into actionable insights efficiently.