8. Advanced Aggregation & Data Processing
Mastering Advanced Aggregation Techniques
The aggregation framework is MongoDB's most powerful feature. This module covers advanced techniques including $facet, $bucket, $graphLookup, $merge, and window functions. These techniques enable complex data processing and analytics.
Advanced aggregation is essential for building sophisticated applications. You can build dashboards, perform time-series analysis, and implement complex business logic. The aggregation framework is composable and extensible. It's built for performance and scalability. Understanding advanced techniques unlocks MongoDB's full potential.
$facet: Multiple Aggregations
$facet allows you to run multiple independent aggregations in a single pipeline. This is perfect for dashboards. You can compute different metrics in parallel. The results are combined into a single output. $facet reduces the number of database round trips. It's efficient and convenient. Use $facet for dashboards and analytics.
const facetPipeline = [ { $facet: { userStats: [ { $count: 'total' }, { $group: { _id: '$city', count: { $sum: 1 } } }, { $sort: { count: -1 } }, { $limit: 10 } ], ageStats: [ { $group: { _id: null, avg: { $avg: '$age' }, max: { $max: '$age' }, min: { $min: '$age' } } } ], tagsStats: [ { $unwind: '$tags' }, { $group: { _id: '$tags', count: { $sum: 1 } } }, { $sort: { count: -1 } } ] } } ]; const results = await collection.aggregate(facetPipeline).toArray(); console.log('Dashboard data:', results[0]);
$graphLookup: Recursive Queries
$graphLookup enables recursive queries for hierarchical data. This is essential for organizational charts, bill-of-materials, and social networks. $graphLookup traverses relationships recursively. It returns the entire hierarchy in one query. This is much more efficient than multiple queries. Use $graphLookup for any recursive data structure.
// Example: Employee hierarchy const graphPipeline = [ { $graphLookup: { from: 'employees', startWith: '$managerId', connectFromField: 'managerId', connectToField: '_id', as: 'reportingChain', maxDepth: 5 } }, { $project: { name: 1, reportingChain: '$reportingChain.name' } } ]; const hierarchy = await employees.aggregate(graphPipeline).toArray(); console.log('Reporting chain:', hierarchy);
Window Functions
Window functions enable calculations across sets of documents related to the current document. This is essential for time-series analysis and moving averages. Window functions use the $setWindowFields stage. You can compute running totals, moving averages, and rankings. Window functions are efficient and expressive. Use them for time-series analytics.
// Calculate moving average const windowPipeline = [ { $setWindowFields: { partitionBy: '$productId', sortBy: { timestamp: 1 }, output: { runningTotal: { $sum: '$sales', window: { documents: ['unbounded', 'current'] } }, movingAvg: { $avg: '$sales', window: { documents: [-2, 'current'] } }, rank: { $rank: {} } } } } ]; const results = await sales.aggregate(windowPipeline).toArray(); console.log('Window calculations:', results);
Knowledge Check
Ready to test your understanding of 8. Advanced Aggregation & Data Processing?