Skip to the page

NoSQL and MongoDB · mid

The aggregation pipeline

An aggregation pipeline is a list of stages. Put $match and $limit early, so fewer documents travel through the later stages.

The notes

What you must know

  • Common stages: $match (filter), $unwind (one output document per array item), $group (summarise), $sort, $limit, $lookup (a join), $project, $merge.
  • Put $match first, so an index is used. Example: { status: 'delivered', createdAt: { $gte: thirtyDaysAgo } } with an index on { status: 1, createdAt: 1 }.
  • Top 5 products by revenue: $match, $unwind the items, $group by productId with $sum of qty times price, $sort by revenue, $limit 5, and only then $lookup the product names.
  • A $sort followed by $limit lets MongoDB keep only the top few while sorting.
  • $unwind multiplies documents by the number of array items, so filter before it.
  • Memory: allowDiskUse, a narrower date range, and an early $project to drop fields.
  • For dashboards, precompute daily totals with $merge into a summary collection.
  • Money should be Decimal128 or integer paise, not double.

The red pen

Common traps: mistake → fix

  • Mistake: $lookup before $limit is fine

    Fix: it runs a lookup for every document; limit first.

  • Mistake: $match after $unwind is the same

    Fix: it is slower and cannot use the index well.

  • Mistake: Doubles are fine for money

    Fix: they give rounding errors.

Easy to hard

Questions interviewers ask, easy to hard

  1. Write a pipeline for the top 5 products by revenue in the last 30 days for delivered orders.
  2. Why does the order of stages matter?
  3. What does $unwind do to the number of documents?

Your first interview is free

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview