SyntaxStudy
Sign Up
MongoDB Aggregation Pipeline Basics
MongoDB Beginner 1 min read

Aggregation Pipeline Basics

The MongoDB aggregation pipeline processes documents through a series of stages, where each stage transforms the data and passes the result to the next stage. The most commonly used stages are $match (filter documents, like a WHERE clause), $group (group documents by a key and compute aggregates), $project (reshape documents by including, excluding, or computing fields), $sort (order documents), $limit and $skip (for pagination), and $unwind (deconstruct an array field into separate documents). Pipelines are expressed as an array of stage objects and can be composed in many ways to implement complex analytics. The aggregation framework runs server-side, so heavy computation happens close to the data.
Example
// Count orders by status
db.orders.aggregate([
  // Stage 1: filter to only 2024 orders
  { $match: { createdAt: { $gte: new Date("2024-01-01") } } },

  // Stage 2: group by status, count and sum total
  { $group: {
      _id: "$status",
      count:    { $sum: 1 },
      revenue:  { $sum: "$total" },
      avgOrder: { $avg: "$total" }
  }},

  // Stage 3: rename _id to status
  { $project: {
      _id: 0,
      status:   "$_id",
      count:    1,
      revenue:  { $round: ["$revenue", 2] },
      avgOrder: { $round: ["$avgOrder", 2] }
  }},

  // Stage 4: sort by revenue descending
  { $sort: { revenue: -1 } }
])