0
0
MongodbHow-ToBeginner · 3 min read

How to Use $facet in Aggregation in MongoDB: Syntax and Examples

Use the $facet stage in MongoDB aggregation to run multiple independent pipelines within a single aggregation query. Each pipeline runs in parallel and outputs its results as separate fields in one document. This helps you get different views or summaries of your data in one query.
📐

Syntax

The $facet stage takes an object where each key is a name for a sub-pipeline, and the value is an array of aggregation stages to run for that sub-pipeline. The output is a single document with fields named after each key, containing the results of each pipeline.

  • Key: Name of the facet (result field).
  • Value: Array of aggregation stages to run.
mongodb
{
  $facet: {
    <facetName1>: [ <pipelineStage1>, <pipelineStage2>, ... ],
    <facetName2>: [ <pipelineStage1>, <pipelineStage2>, ... ],
    ...
  }
}
💻

Example

This example shows how to use $facet to get two results from a sales collection: total sales by category and the top 3 highest sales.

mongodb
db.sales.aggregate([
  {
    $facet: {
      totalSalesByCategory: [
        { $group: { _id: "$category", total: { $sum: "$amount" } } },
        { $sort: { total: -1 } }
      ],
      topSales: [
        { $sort: { amount: -1 } },
        { $limit: 3 }
      ]
    }
  }
])
Output
[ { "totalSalesByCategory": [ { "_id": "Electronics", "total": 5000 }, { "_id": "Books", "total": 3000 } ], "topSales": [ { "_id": ObjectId("..."), "category": "Electronics", "amount": 2000 }, { "_id": ObjectId("..."), "category": "Books", "amount": 1500 }, { "_id": ObjectId("..."), "category": "Electronics", "amount": 1300 } ] } ]
⚠️

Common Pitfalls

Common mistakes when using $facet include:

  • Using $facet without wrapping pipelines in arrays, which causes syntax errors.
  • Expecting $facet to output multiple documents instead of one document with multiple fields.
  • Not handling empty results in one facet, which still returns an empty array but can confuse processing.

Always remember each facet's pipeline must be an array of stages.

mongodb
/* Wrong usage: pipelines not in arrays */
db.collection.aggregate([
  {
    $facet: {
      facet1: { $match: { status: "A" } },  // Incorrect
      facet2: { $group: { _id: "$category", count: { $sum: 1 } } }  // Incorrect
    }
  }
])

/* Correct usage: pipelines as arrays */
db.collection.aggregate([
  {
    $facet: {
      facet1: [ { $match: { status: "A" } } ],
      facet2: [ { $group: { _id: "$category", count: { $sum: 1 } } } ]
    }
  }
])
📊

Quick Reference

  • $facet: Runs multiple pipelines in parallel inside one aggregation.
  • Each pipeline is an array of stages.
  • Output is a single document with fields named after each pipeline.
  • Useful for multi-view reports or summaries in one query.

Key Takeaways

Use $facet to run multiple aggregation pipelines in parallel and get combined results in one document.
Each facet pipeline must be an array of aggregation stages.
The output document has fields named after each facet with their respective results as arrays.
Common errors include forgetting to wrap pipelines in arrays and expecting multiple documents instead of one.
$facet is great for generating multiple summaries or views from the same dataset in one query.