SyntaxStudy
Sign Up
MongoDB Beginner 1 min read

Advanced Pipeline Stages

Beyond the core stages, MongoDB provides several powerful aggregation operators for advanced analytics. $bucket and $bucketAuto categorise documents into ranges (like histogram bins). $facet runs multiple sub-pipelines in parallel and returns all results in a single document — ideal for building faceted search results. $addFields (alias $set) adds computed fields without replacing the whole document. $replaceRoot promotes a nested document to become the top-level document. $out and $merge write pipeline results to a collection, enabling materialised view patterns. Accumulator expressions such as $sum, $avg, $min, $max, $first, $last, $push, and $addToSet are used inside $group to compute aggregates per group.
Example
// $bucket — group products into price ranges
db.products.aggregate([
  { $bucket: {
      groupBy: "$price",
      boundaries: [0, 50, 100, 250, 500, 1000],
      default: "1000+",
      output: { count: { $sum: 1 }, products: { $push: "$name" } }
  }}
])

// $facet — parallel sub-pipelines for faceted search
db.products.aggregate([
  { $match: { inStock: true } },
  { $facet: {
      byCategory: [
        { $group: { _id: "$category", count: { $sum: 1 } } }
      ],
      byPriceRange: [
        { $bucket: {
            groupBy: "$price",
            boundaries: [0, 100, 500, 1000],
            default: "other"
        }}
      ],
      totalCount: [
        { $count: "total" }
      ]
  }}
])

// $addFields — compute new fields
db.orders.aggregate([
  { $addFields: {
      taxAmount:  { $multiply: ["$total", 0.08] },
      grandTotal: { $multiply: ["$total", 1.08] }
  }}
])