Build MongoDB aggregation pipelines — $match, $group, $lookup, $project, index optimization. Triggers: 'aggregation', 'pipeline', 'complex query', '$group', '$lookup', 'reporting query'.
Build and optimize MongoDB aggregation pipelines for complex queries and reporting.
$match to filter early and reduce the working set.$lookup for joins; prefer pipeline sub-queries over simple localField/foreignField when you need to filter or project the joined data.$unwind after $lookup only when you need to flatten arrays for grouping.$group for aggregation: $sum, $avg, $min, $max, $push, $addToSet.$project or $addFields to reshape output.$sort and $limit at the end for pagination or top-N queries.// Template
const pipeline = [
{ $match: { status: 'completed', createdAt: { $gte: startDate, $lte: endDate } } },
{ $group: { _id: '$category', total: { $sum: '$amount' }, count: { $sum: 1 } } },
{ $sort: { total: -1 } },
{ $limit: 10 },
];
const results = await Order.aggregate(pipeline);
$match stage fields.$match and $sort as early as possible to leverage indexes.explain('executionStats') to verify index usage and scan counts.$lookup, ensure the foreign collection has an index on the join field.$unwind on large arrays when $filter or $reduce can achieve the same result.src/services/<domain>Service.js (e.g., src/services/reportService.js).$match dynamically.seed-data skill to populate test collections.$match is the first stage (or as early as possible).explain().