4 Hours

4. Aggregation Framework: Data Processing Pipeline

Aggregation

The Aggregation Pipeline: MongoDB's Data Processing Engine

The aggregation framework is MongoDB's most powerful feature for data processing and analytics. It allows you to process, transform, and analyze data using a pipeline of stages. The aggregation pipeline is similar to a Unix pipe — documents flow through stages that transform them.

The aggregation framework is essential for analytics, reporting, and complex data transformations. You can filter, group, sort, project, join, and compute data. The aggregation framework is faster and more efficient than MapReduce. It's built for performance and scalability. Understanding the aggregation framework is essential for unlocking MongoDB's full potential. The pipeline stages are composable, allowing you to build complex data processing workflows. The aggregation framework supports a wide range of operations, from simple filtering to complex analytics.

Core Pipeline Stages

The aggregation pipeline consists of stages that process documents. The $match stage filters documents. The $group stage groups documents by a key. The $project stage reshapes documents. The $sort stage sorts documents. The $limit and $skip stages paginate results. The $unwind stage deconstructs arrays. The $lookup stage performs joins. These stages cover most data processing needs. The pipeline is executed on the server, making it efficient for large datasets. You can combine stages to build complex workflows.

JavaScript
// Basic aggregation: group by city and count users
const pipeline = [
  { $match: { age: { $gte: 18 } } },
  { $group: { _id: '$city', count: { $sum: 1 } } },
  { $sort: { count: -1 } },
  { $limit: 10 }
];

const results = await collection.aggregate(pipeline).toArray();

// Unwind an array
const unwindPipeline = [
  { $unwind: '$tags' },
  { $group: { _id: '$tags', count: { $sum: 1 } } }
];

// Join with $lookup
const lookupPipeline = [
  {
    $lookup: {
      from: 'posts',
      localField: '_id',
      foreignField: 'userId',
      as: 'posts'
    }
  }
];

Grouping and Aggregation Operators

The $group stage is central to aggregation. It groups documents by a key and computes aggregated values. The $sum operator sums values. The $avg operator computes averages. The $min and $max operators find extremes. The $push operator creates an array of values. The $addToSet operator creates an array of unique values. These operators enable powerful analytics. You can group by multiple fields and compute multiple aggregates simultaneously.

JavaScript
// Complex grouping
const complexGroup = [
  {
    $group: {
      _id: {
        city: '$city',
        ageGroup: {
          $cond: [
            { $lt: ['$age', 25] }, 'under25',
            { $lt: ['$age', 35] }, '25-34',
            '35+'
          ]
        }
      },
      totalUsers: { $sum: 1 },
      averageAge: { $avg: '$age' },
      minAge: { $min: '$age' },
      maxAge: { $max: '$age' },
      emails: { $push: '$email' },
      uniqueTags: { $addToSet: '$tags' }
    }
  }
];

Advanced Aggregation Techniques

The aggregation framework supports advanced techniques. The $facet stage creates multiple aggregations in one pipeline. The $bucket stage creates histogram buckets. The $window stage performs window calculations. The $graphLookup stage performs recursive graph traversal. These techniques enable complex analytics and reporting. Use $facet for dashboards. Use $bucket for histograms. Use $window for moving averages. These techniques are essential for advanced data processing.

JavaScript
// $facet: Multiple aggregations in one pipeline
const facetPipeline = [
  {
    $facet: {
      totalUsers: [
        { $count: 'count' }
      ],
      byCity: [
        { $group: { _id: '$city', count: { $sum: 1 } } },
        { $sort: { count: -1 } }
      ],
      ageStats: [
        { $group: { _id: null, avg: { $avg: '$age' }, min: { $min: '$age' }, max: { $max: '$age' } } }
      ]
    }
  }
];

// $bucket: Histogram
const bucketPipeline = [
  {
    $bucket: {
      groupBy: '$age',
      boundaries: [18, 25, 35, 50, 65],
      default: '65+',
      output: {
        count: { $sum: 1 },
        names: { $push: '$name' }
      }
    }
  }
];

Knowledge Check

Ready to test your understanding of 4. Aggregation Framework: Data Processing Pipeline?

Back