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.
$facetstage 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
$facetstage only once.
$facetenables various aggregations on the same set of input documents, without needing to retrieve the input documents multiple times.
$facetstage has the following form:
Specify the output field name for each specified pipeline.
Facet-related aggregation stages categorize and group incoming documents. Specify any of the following facet-related stages within different
<stage> to perform a multi-faceted aggregation:
Any other aggregation stages can also be used with
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.
Consider an online store whose inventory is stored in the following
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
$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: