> For the complete MongoDB documentation index, see www.mongodb.com/docs/llms.txt

<!--
Tab options on this page. Append to the .md URL to filter:
  ?tabs=<id,...>   select specific tabs (e.g. ?tabs=nodejs,shell)
  ?allTabs=true    include every tab
  (no param)       default: one tab per tabset

Available tabs:
  drivers: shell, csharp, nodejs
-->

# $facet (aggregation stage)

## Definition

Processes multiple [aggregation pipelines](https://www.mongodb.com/docs/manual/core/aggregation-pipeline.md#std-label-aggregation-pipeline) within a single stage on the same set of input documents. Each sub-pipeline has its own field in the output document where its results are stored as an array of documents.

The `$facet` stage allows you to create multi-faceted aggregations which characterize data across multiple dimensions, or facets, within a single aggregation stage. Multi-faceted aggregations provide multiple filters and categorizations to guide data browsing and analysis. Retailers commonly use faceting to narrow search results by creating filters on product price, manufacturer, size, etc.

Input documents are passed to the `$facet` stage only once, enabling various aggregations on the same set of input documents.

## Compatibility

You can use `$facet` for deployments hosted in the following environments:

- [MongoDB Atlas](https://www.mongodb.com/docs/atlas): The fully managed service for MongoDB deployments in the cloud

* [MongoDB Enterprise](https://www.mongodb.com/docs/manual/administration/install-enterprise.md#std-label-install-mdb-enterprise): The subscription-based, self-managed version of MongoDB

* [MongoDB Community](https://www.mongodb.com/docs/manual/administration/install-community.md#std-label-install-mdb-community-edition): The source-available, free-to-use, and self-managed version of MongoDB

## Syntax

The `$facet` stage has the following form:

```javascript
{ $facet:
    {
      <outputField1>: [ <stage1>, <stage2>, ... ],
      <outputField2>: [ <stage1>, <stage2>, ... ],
      ...

    }
}
```

Specify the output field name for each specified pipeline.

## Considerations

As each stage in a `$facet` executes, the resulting document is limited to 100 megabytes. Note the [allowDiskUse](https://www.mongodb.com/docs/manual/reference/command/aggregate.md#std-label-aggregate-cmd-allowDiskUse) flag doesn't affect the 100 megabyte size limit, since `$facet` can't spill to disk.

If a `$facet` stage constructs a document where the size exceeds the 100 megabyte limit, MongoDB returns an [`ExceededMemoryLimit`](https://www.mongodb.com/docs/manual/reference/error-codes.md#mongodb-error-146) error.

The final output document is subject to the 16 mebibyte [BSON document size limit](https://www.mongodb.com/docs/manual/reference/limits.md#mongodb-limit-BSON-Document-Size). If it exceeds 16 mebibytes, the aggregation produces an error.

**See also:**

[Aggregation Pipeline Limits](https://www.mongodb.com/docs/manual/core/aggregation-pipeline-limits.md#std-label-agg-pipeline-limits)

## Behavior

Facet-related aggregation stages categorize and group incoming documents. Specify any of the following facet-related stages within different `$facet` sub-pipeline's `<stage>` to perform a multi-faceted aggregation:

- [`$bucket`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/bucket.md#mongodb-pipeline-pipe.-bucket)

- [`$bucketAuto`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/bucketauto.md#mongodb-pipeline-pipe.-bucketAuto)

- [`$sortByCount`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/sortbycount.md#mongodb-pipeline-pipe.-sortByCount)

Other [aggregation stages](https://www.mongodb.com/docs/manual/reference/mql/aggregation-stages.md#std-label-aggregation-pipeline-operator-reference) can also be used with `$facet` with the following exceptions:

- [`$collStats`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/collstats.md#mongodb-pipeline-pipe.-collStats)

- `$facet`

- [`$geoNear`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/geonear.md#mongodb-pipeline-pipe.-geoNear)

- [`$indexStats`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/indexstats.md#mongodb-pipeline-pipe.-indexStats)

- [`$out`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/out.md#mongodb-pipeline-pipe.-out)

- [`$merge`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/merge.md#mongodb-pipeline-pipe.-merge)

- [`$planCacheStats`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/plancachestats.md#mongodb-pipeline-pipe.-planCacheStats)

- [`$search`](https://www.mongodb.com/docs/search/query/aggregation-stages/search.md#mongodb-pipeline-pipe.-search)

- [`$searchMeta`](https://www.mongodb.com/docs/search/query/aggregation-stages/searchMeta.md#mongodb-pipeline-pipe.-searchMeta)

- [`$vectorSearch`](https://www.mongodb.com/docs/vector-search/query/aggregation-stages/vector-search-stage.md#mongodb-pipeline-pipe.-vectorSearch)

Each sub-pipeline within `$facet` is passed the exact same set of input documents. These sub-pipelines are completely independent of one another and the document array output by each is stored in separate fields in the output document. The output of one sub-pipeline can not be used as the input for a different sub-pipeline within the same `$facet` stage. If further aggregations are required, add additional stages after `$facet` and specify the field name, `<outputField>`, of the desired sub-pipeline output.

### Index Use

Pipeline order determines how the `$facet` stage uses indexes.

- If the `$facet` stage is the first stage in a pipeline, the stage will perform a `COLLSCAN`. The `$facet` stage does not make use of indexes if it is the first stage in the pipeline.

- If the `$facet` stage comes later in the pipeline and earlier stages have used indexes, `$facet` will not trigger a `COLLSCAN` during execution.

For example, [`$match`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/match.md#mongodb-pipeline-pipe.-match) or [`$sort`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/sort.md#mongodb-pipeline-pipe.-sort) stages that come before a `$facet` stage can make use of indexes and the `$facet` will not trigger a `COLLSCAN`.

For optimization suggestions, see: [Aggregation Pipeline Optimization.](https://www.mongodb.com/docs/manual/core/aggregation-pipeline-optimization.md#std-label-agg-pipeline-optimization)

## Examples

### MongoDB Shell

The examples on this page use data from the [sample\_mflix dataset](https://www.mongodb.com/docs/manual/sample-data/sample-mflix.md#std-label-sample-mflix). For details on how to load this dataset into your self-managed MongoDB deployment, see [Load the Sample Dataset](https://www.mongodb.com/docs/manual/sample-data/load-sample-data-local.md#std-label-sample-dataset-local). If you made any modifications to the sample databases, you may need to drop and recreate the databases to run the examples on this page.

The following aggregation pipeline uses the `movies` collection to categorize films across multiple dimensions. A [`$match`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/match.md#mongodb-pipeline-pipe.-match) stage limits the input to movies with a runtime greater than 1,000 minutes. The `$facet` stage runs three sub-pipelines in parallel using [`$sortByCount`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/sortbycount.md#mongodb-pipeline-pipe.-sortByCount), [`$bucket`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/bucket.md#mongodb-pipeline-pipe.-bucket), and [`$bucketAuto`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/bucketauto.md#mongodb-pipeline-pipe.-bucketAuto). MongoDB fetches input documents from the `movies` collection only once, at the beginning of the operation:

```javascript
db.movies.aggregate( [
  { $match: { runtime: { $gt: 1000 } } },
  {
    $facet: {
      "categorizedByGenres": [
        { $unwind: "$genres" },
        { $sortByCount: "$genres" }
      ],
      "categorizedByRuntime": [
        {
          $bucket: {
            groupBy: "$runtime",
            boundaries: [ 1000, 1200, 1400 ],
            default: "Other",
            output: {
              "count": { $sum: 1 },
              "titles": { $push: "$title" }
            }
          }
        }
      ],
      "categorizedByYear(Auto)": [
        {
          $bucketAuto: {
            groupBy: "$year",
            buckets: 4
          }
        }
      ]
    }
  }
] )

```

**Output:**

```javascript
[
  {
    categorizedByGenres: [
      { _id: 'Sport', count: 1 },
      { _id: 'Documentary', count: 1 },
      { _id: 'Action', count: 1 },
      { _id: 'Drama', count: 1 },
      { _id: 'Adventure', count: 1 },
      { _id: 'History', count: 1 }
    ],
    categorizedByRuntime: [
      { _id: 1000, count: 1, titles: [ 'Baseball' ] },
      { _id: 1200, count: 1, titles: [ 'Centennial' ] }
    ],
    'categorizedByYear(Auto)': [
      { _id: { min: 1978, max: 1994 }, count: 1 },
      { _id: { min: 1994, max: 1994 }, count: 1 }
    ]
  }
]

```

## Learn More

To learn more about related pipeline stages, see the [`$bucketAuto`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/bucketauto.md#mongodb-pipeline-pipe.-bucketAuto), [`$sortByCount`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/sortbycount.md#mongodb-pipeline-pipe.-sortByCount), and [`$limit`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/limit.md#mongodb-pipeline-pipe.-limit) guides.
