MongoDB Aggregation Pipeline Patterns/Run multiple result sets with $facet

Produce multiple related aggregations in one pipeline.

Section: Advanced stages

Run multiple result sets with $facet

javascript
javascript
db.orders.aggregate([
  {
    $facet: {
      totalsByStatus: [
        { $group: { _id: "$status", count: { $sum: 1 } } }
      ],
      recentOrders: [
        { $sort: { created_at: -1 } },
        { $limit: 5 }
      ]
    }
  }
])
Explanation

`$facet` is handy when one request needs several summary blocks.

Learn the surrounding workflow

Compare similar commands or jump into common fixes when this command is part of a bigger troubleshooting path.

Related commands

Same sheet · prioritizing Advanced stages
Bucket data for reporting
Group values into explicit ranges.
OpenIn sheetjavascriptsame section
Count pipeline output
Return a final count after filters and transforms.
OpenIn sheetjavascriptsame section
Sum revenue by status
Filter first, then group and sum.
OpenIn sheetjavascript2 tag match
Project computed fields
Shape output and derive new values.
OpenIn sheetjavascript2 tag match
Unwind an array
Turn array elements into separate pipeline rows.
OpenIn sheetjavascript2 tag match
Join with another collection
Use `$lookup` for collection-to-collection joins.
OpenIn sheetjavascript2 tag match