Aggregation Pipeline

1/10/2025

Aggregation Pipeline

The aggregation pipeline is a framework for data processing and transformation.

Basic Pipeline

javascript
db.orders.aggregate([
  { $match: { status: 'completed' } },
  { $group: {
    _id: '$customerId',
    total: { $sum: '$amount' }
  }},
  { $sort: { total: -1 } }
])

Common Stages

javascript
// $match - Filter documents
{ $match: { age: { $gte: 21 } } }

// $group - Group by field
{ $group: {
  _id: '$category',
  count: { $sum: 1 },
  avgPrice: { $avg: '$price' }
}}

// $project - Shape output
{ $project: {
  name: 1,
  total: { $multiply: ['$price', '$quantity'] }
}}

// $sort - Order results
{ $sort: { createdAt: -1 } }

// $limit and $skip
{ $limit: 10 }
{ $skip: 20 }

Lookup (Join)

javascript
db.orders.aggregate([
  {
    $lookup: {
      from: 'users',
      localField: 'userId',
      foreignField: '_id',
      as: 'user'
    }
  },
  { $unwind: '$user' }
])