Multi-Stage Aggregation Pipelines

Multi-Stage Aggregation Pipelines in NoSQL Databases: The Aggregation Framework is MongoDB's built-in data processing engine.

The Aggregation Framework is MongoDB's built-in data processing engine. It models data operations as an assembly pipeline where documents enter stage 1, are transformed, and pass to subsequent stages.


1. Real-World Revenue Analytics Pipeline

db.orders.aggregate([
  // Stage 1: Filter only completed transactions within year 2026
  {
    $match: {
      status: "COMPLETED",
      created_at: {
        $gte: ISODate("2026-01-01T00:00:00Z"),
        $lt: ISODate("2027-01-01T00:00:00Z")
      }
    }
  },

  // Stage 2: Group by product category and calculate aggregations
  {
    $group: {
      _id: "$category",
      total_revenue: { $sum: "$total_amount" },
      average_order_value: { $avg: "$total_amount" },
      total_units_sold: { $sum: "$quantity" },
      order_count: { $sum: 1 }
    }
  },

  // Stage 3: Filter groups with significant sales volume
  {
    $match: {
      total_revenue: { $gte: 10000 }
    }
  },

  // Stage 4: Reshape output document fields
  {
    $project: {
      _id: 0,
      category: "$_id",
      revenue: { $round: ["$total_revenue", 2] },
      average_ticket: { $round: ["$average_order_value", 2] },
      units: "$total_units_sold"
    }
  },

  // Stage 5: Sort highest revenue first
  {
    $sort: { revenue: -1 }
  }
]);

2. Array Unwinding ($unwind)

To calculate statistics on elements inside an array, $unwind deconstructs the array field, emitting one output document for each array element:

// Unwind all line items and calculate top-selling items
db.orders.aggregate([
  { $unwind: "$items" },
  {
    $group: {
      _id: "$items.sku",
      total_purchased: { $sum: "$items.quantity" },
      gross_sales: { $sum: { $multiply: ["$items.quantity", "$items.unit_price"] } }
    }
  },
  { $sort: { gross_sales: -1 } },
  { $limit: 5 }
]);