Chuyển đến nội dung

Bài 26 · Aggregation

Facets, Buckets and Aggregation Pagination

Build search result pages and dashboards with Mongoose aggregation - $facet for several results at once, $bucket histograms, $dateToString time series and paginated pipelines with total counts.

A product search page shows three things at once: the current page of results, the total number of matches, and a list of filters with counts ("Under $20 (14)", "Pens (9)"). Running separate queries triples the work. MongoDB's $facet runs several sub-pipelines over the same input in one pass. This lesson also covers histograms with $bucket, time series grouping, and pagination.

It continues from group and lookup.

$facet: several results from one match

$facet takes an object whose keys are names and whose values are sub-pipelines. Each sub-pipeline receives every document that reached the $facet stage, and the output is one document with one array per name.

JavaScript
const [page] = await Product.aggregate([
  { $match: { active: true, category: 'pens' } },
  {
    $facet: {
      items: [
        { $sort: { price: 1 } },
        { $skip: 0 },
        { $limit: 20 },
        { $project: { name: 1, price: 1 } },
      ],
      total: [{ $count: 'n' }],
      byBrand: [
        { $group: { _id: '$brand', count: { $sum: 1 } } },
        { $sort: { count: -1 } },
      ],
    },
  },
]);
// page = { items: [...], total: [{ n: 53 }], byBrand: [...] }

Notes: total is an array (take page.total[0]?.n ?? 0). The $match before $facet can use an index; stages inside a facet cannot, so do the filtering first. The output document must stay under 16 MB, so always $limit the item list.

Node.js One pass, several answers (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

$bucket and $bucketAuto: histograms

$bucket groups documents into ranges you define, great for price bands or age groups.

JavaScript
await Product.aggregate([
  {
    $bucket: {
      groupBy: '$price',
      boundaries: [0, 5, 20, 100],   // [0,5) [5,20) [20,100)
      default: 'other',              // anything outside the boundaries
      output: { count: { $sum: 1 }, names: { $push: '$name' } },
    },
  },
]);

Boundaries are lower-inclusive, upper-exclusive and must be sorted. Without default, a value outside the boundaries makes the stage fail. $bucketAuto picks boundaries for you so each bucket has roughly the same number of documents: { $bucketAuto: { groupBy: '$price', buckets: 4 } }.

Node.js Price histogram (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Time series with date operators

Group by day, month or hour using $dateToString or the $year/$month operators. Make sure your createdAt field is a real Date.

JavaScript
await Order.aggregate([
  { $match: { createdAt: { $gte: new Date('2026-01-01') } } },
  {
    $group: {
      _id: { $dateToString: { format: '%Y-%m', date: '$createdAt' } },
      revenue: { $sum: '$amount' },
    },
  },
  { $sort: { _id: 1 } },
]);

$dateToString accepts a timezone option ('Europe/Berlin'), and without it uses UTC. Day boundaries differ by time zone, so pick one on purpose.

Node.js Revenue per month (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Pagination inside a pipeline

There are three ways, from simplest to most scalable:

  1. $skip + $limit: easy, but MongoDB must walk past all skipped documents, so page 5000 is slow.
  2. $facet with items and total: one round trip for both the page and the count, as above.
  3. Range (keyset) pagination: remember the last seen sort key and ask for "everything after it". It stays fast on any page because an index jumps straight to the position.
JavaScript
// next page after the last item you showed (sorted by createdAt desc, _id desc)
await Post.aggregate([
  {
    $match: {
      $or: [
        { createdAt: { $lt: lastCreatedAt } },
        { createdAt: lastCreatedAt, _id: { $lt: lastId } },
      ],
    },
  },
  { $sort: { createdAt: -1, _id: -1 } },
  { $limit: 20 },
]);

Include _id as a tiebreaker because many documents can share a timestamp. Keyset pagination cannot jump to "page 37", but infinite scroll and "next" links do not need that. More patterns in Lean, select and pagination.

Other useful stages and operators

  • $sortByCount: '$field': shorthand for group-by-field, count, sort descending.
  • $sample: { size: 5 }: random documents.
  • $replaceRoot / $replaceWith: promote a nested object to the top level.
  • $merge / $out: write the pipeline result into a collection (materialized views, nightly reports).
  • $setWindowFields: running totals and moving averages.
  • $cond, $switch, $ifNull: conditionals inside expressions.
Node.js Keyset pagination (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Check your understanding

Quick check · 4 questions

of 4 answered You scored / 4 · perfect!

  1. 1. What does $facet give you?

    Each named sub-pipeline receives all input documents; the result is a single document with one array per name.
  2. 2. What happens in $bucket when a value falls outside boundaries and no default is set?

    Provide a default bucket to catch out-of-range values, otherwise the aggregation fails.
  3. 3. Which pagination style stays fast on very deep pages?

    Skip must scan all skipped documents; a keyset filter uses an index to jump to the position.
  4. 4. Where should the main filter go relative to $facet?

    Stages inside $facet cannot use indexes, so filter first and facet the smaller set.

Summary

  • $facet returns a page, its total and filter counts from one pass.
  • $bucket/$bucketAuto make histograms; boundaries are lower-inclusive.
  • Group by $dateToString for time series, and choose a time zone deliberately.
  • Use $skip for small pages, $facet for counts, and keyset pagination for deep or infinite lists.
  • Filter before $facet and cap the item list at a $limit.

Next: Indexes in Mongoose

Theo dõi tiến độ của bạn

Tạo tài khoản miễn phí để đánh dấu bài đã học và tiếp tục từ chỗ bạn dừng lại trên mọi thiết bị.