- Reference >
- Operators >
- Aggregation Pipeline Stages >
- $facet (aggregation)
$facet (aggregation)¶
On this page
Definition¶
-
$facet
¶ New in version 3.4.
Processes multiple aggregation pipelines 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.$facet
enables various aggregations on the same set of input documents, without needing to retrieve the input documents multiple times.The
$facet
stage has the following form:Specify the output field name for each specified pipeline.
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:
Other
aggregation stages can
also be used with $facet
with the following exceptions:
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.
Example¶
Consider an online store whose inventory is stored in the following
artwork
collection:
The following operation uses MongoDB’s faceting features to provide
customers with the store’s inventory categorized across multiple
dimensions such as tags, price, and year created. This
$facet
stage has three sub-pipelines that use
$sortByCount
, $bucket
, or
$bucketAuto
to perform this multi-faceted aggregation.
The input documents from artwork
are fetched from the database only
once, at the beginning of the operation:
The operation returns the following document: