TExcelTAD
Home › MongoDB › Aggregation $facet

Aggregation $facet

$facet runs several sub-pipelines on the same input in a single stage and returns one document containing each sub-pipeline's results as an array. The typical use is a search or shop page that shows the results and the counts per category, price range and so on, all from one query.

js
{ $facet: {
    <name1>: [ <stages> ],
    <name2>: [ <stages> ],
    …
} }

A product-listing page

mongosh · try it yourself
const page = db.products.aggregate([
  { $match: { stock: { $gt: 0 } } },
  { $facet: {
      byCategory: [{ $sortByCount: '$category' }, { $sort: { count: -1, _id: 1 } }],
      byPrice: [{ $bucket: { groupBy: '$price', boundaries: [0, 10, 25, 100] } }],
      topRated: [{ $sort: { rating: -1, _id: 1 } }, { $limit: 3 }, { $project: { _id: 0, name: 1, rating: 1 } }],
      total: [{ $count: 'n' }]
  } }
]).toArray()[0];

print('categories:', page.byCategory);
print('prices:', page.byPrice);
print('top rated:', page.topRated);
print('in stock:', page.total[0].n);
categories: [
  { _id: 'equipment', count: 5 },
  { _id: 'coffee', count: 4 },
  { _id: 'snacks', count: 3 },
  { _id: 'tea', count: 3 },
  { _id: 'merch', count: 1 }
]
prices: [ { _id: 0, count: 5 }, { _id: 10, count: 6 }, { _id: 25, count: 5 } ]
top rated: [
  { name: 'Ethiopia Yirgacheffe', rating: 4.9 },
  { name: 'Pour-Over Dripper', rating: 4.8 },
  { name: 'Dark Chocolate Bar', rating: 4.8 }
]
in stock: 16

The $match before $facet ran once; every facet started from the same 16 in-stock products.

Results and total count together

Pagination usually needs the current page and the total number of results (to draw "page 2 of 5"). $facet gets both in one round trip:

mongosh · try it yourself
const [res] = db.orders.aggregate([
  { $match: { status: { $in: ['delivered', 'shipped'] } } },
  { $sort: { date: -1 } },
  { $facet: {
      rows: [{ $skip: 4 }, { $limit: 4 }, { $project: { total: 1 } }],
      meta: [{ $count: 'total' }]
  } }
]).toArray();
print('page 2 rows:', res.rows.map(o => o._id));
print('total results:', res.meta[0].total, '-> pages:', Math.ceil(res.meta[0].total / 4));
page 2 rows: [ 1010, 1009, 1008, 1007 ]
total results: 13 -> pages: 4

Reshaping the facet output

Since $facet outputs one document, later stages can combine its arrays. Here a small KPI summary is built:

mongosh · try it yourself
print(db.orders.aggregate([
  { $facet: {
      open: [{ $match: { status: { $in: ['processing', 'shipped'] } } }, { $count: 'n' }],
      revenue: [{ $match: { status: 'delivered' } }, { $group: { _id: null, sum: { $sum: '$total' } } }]
  } },
  { $project: {
      openOrders: { $first: '$open.n' },
      deliveredRevenue: { $first: '$revenue.sum' }
  } }
]).toArray());
[ { openOrders: 8, deliveredRevenue: 480 } ]

Rules and limits

  • Each sub-pipeline receives the full input of the $facet stage and works independently.
  • Sub-pipelines can't contain $out, $merge, another $facet, or a few other special stages.
  • Sub-pipelines inside $facet can't use indexes: put $match and $sort that should use an index before $facet.
  • The output is a single document, so it is subject to the 16 MB document limit. Limit each facet's results.

Test yourself

How many documents does a $facet stage output?

  1. One per facet
  2. One per input document
  3. Exactly one
  4. Zero

Where should a $match that can use an index go?

  1. Inside each facet
  2. Before the $facet stage
  3. After the $facet stage
  4. It doesn't matter