MongoDB

MongoDB Aggregation Tuning in Production (and Fixing Cassandra Hotspots)

How to speed up slow MongoDB aggregation pipelines: explain(), stage ordering, ESR indexes, $lookup cost, plus a note on Cassandra partition key hotspots.

Slow aggregation pipelines rarely need a bigger server. They need the right stage order and the right index. After tuning pipelines in production and re-modeling Cassandra partition keys, we cut average query response from about 820ms to 450ms. Here is the method.

1. Start with explain, not intuition

Run the pipeline with execution statistics and read what actually happened:

db.orders.explain("executionStats").aggregate([
  { $match: { status: "paid", createdAt: { $gte: ISODate("2026-01-01") } } },
  { $sort:  { createdAt: -1 } },
  { $limit: 100 }
])

Compare totalDocsExamined and totalKeysExamined to nReturned. If you examine 2 million documents to return 100, you have an index problem. Seeing COLLSCAN on a large collection is the clearest red flag.

2. Filter and shrink early

  • Put $match as early as possible so every later stage sees fewer documents. The optimizer can move some stages for you, but never rely on it.
  • Use $project (or $unset) early to drop big fields you do not need.
  • Do $match and $limit before $lookup, so you join 100 documents, not 2 million.
// Slow: join everything, then filter
[ { $lookup: { from: "customers", localField: "customerId", foreignField: "_id", as: "c" } },
  { $match:  { status: "paid" } } ]

// Fast: filter first, then join the survivors
[ { $match:  { status: "paid" } },
  { $lookup: { from: "customers", localField: "customerId", foreignField: "_id", as: "c" } } ]

3. Build indexes with the ESR rule

For compound indexes, order fields as Equality, Sort, Range. For the first pipeline above (equality on status, sort and range on createdAt):

db.orders.createIndex({ status: 1, createdAt: -1 })

Only the leading $match/$sort stages can use an index. Once a pipeline reaches $group or $project, later stages work on in-memory results.

4. Treat $lookup as a join with a price tag

  • Make sure foreignField is indexed on the joined collection. Without it, each input document triggers a scan.
  • If you join the same data on every read, consider embedding or denormalizing it. MongoDB rewards modeling for your access pattern.
  • Avoid $unwind on very large arrays unless you must; it multiplies documents.

5. Watch memory and disk spills

Blocking stages such as $group and $sort have per-stage memory limits (historically 100 MB; check your server version). Exceeding them either errors or, with allowDiskUse: true, spills to disk and slows down. Treat spilling as a signal to reduce data earlier or add a supporting index, not as a fix.

6. Bonus: Cassandra hotspots are a data-model problem

If one Cassandra node runs hot, the partition key is usually the cause: too many writes land in one partition (for example a single "today" bucket). Spread the load by adding a high-cardinality component or a time bucket to the partition key and keep partitions reasonably sized:

CREATE TABLE events_by_device (
  device_id text,
  day       date,
  ts        timestamp,
  payload   text,
  PRIMARY KEY ((device_id, day), ts)
) WITH CLUSTERING ORDER BY (ts DESC);

Query by the full partition key to hit one partition, and avoid ALLOW FILTERING in production paths.

Checklist

  1. explain("executionStats") every slow pipeline.
  2. $match and $limit first; $project early.
  3. Index with Equality, Sort, Range.
  4. Index foreignField for every $lookup.
  5. Re-check after each change and keep before/after numbers.

Enjoyed this?

I write about PostgreSQL, AWS and database reliability. Have a question or a similar problem to solve?