MongoDB Aggregation Pipeline Patterns

Group, project, sort, unwind, lookup, facet, and aggregate analytics data with MongoDB pipelines.

View
StandardDetailedCompact
Export
Copy the compact sheet, download it, or print it.
Download
`D` dense toggle · `C` copy all
## Core stages
Sum revenue by status
db.orders.aggregate([
  { $match: { status: "paid" } },
  { $group: { _id: "$country", revenue: { $sum: "$total" }, orders: { $sum: 1 } } },
  { $sort: { revenue: -1 } }
])

# Filter first, then group and sum.

Project computed fields
db.orders.aggregate([
  { $project: { customer_id: 1, total: 1, tax: { $multiply: ["$total", 0.08] } } }
])

# Shape output and derive new values.

Unwind an array
db.orders.aggregate([
  { $unwind: "$items" },
  { $group: { _id: "$items.sku", units: { $sum: "$items.qty" } } },
  { $sort: { units: -1 } }
])

# Turn array elements into separate pipeline rows.

Join with another collection
db.orders.aggregate([
  {
    $lookup: {
      from: "users",
      localField: "user_id",
      foreignField: "_id",
      as: "user"
    }
  },
  { $unwind: "$user" }
])

# Use `$lookup` for collection-to-collection joins.

## Advanced stages
Run multiple result sets with $facet
db.orders.aggregate([
  {
    $facet: {
      totalsByStatus: [
        { $group: { _id: "$status", count: { $sum: 1 } } }
      ],
      recentOrders: [
        { $sort: { created_at: -1 } },
        { $limit: 5 }
      ]
    }
  }
])

# Produce multiple related aggregations in one pipeline.

Bucket data for reporting
db.orders.aggregate([
  {
    $bucket: {
      groupBy: "$total",
      boundaries: [0, 50, 100, 500, 1000],
      default: "1000+",
      output: { count: { $sum: 1 } }
    }
  }
])

# Group values into explicit ranges.

Count pipeline output
db.orders.aggregate([
  { $match: { status: "paid" } },
  { $count: "paid_orders" }
])

# Return a final count after filters and transforms.

Recommended next

No recommendations yet.