Skip to the page

NoSQL and MongoDB · mid

MongoDB indexes, the ESR rule and explain

A compound index works best when its fields are ordered Equality, then Sort, then Range. You check it with explain and by looking at keys examined against documents returned.

The notes

What you must know

  • ESR guideline: put Equality fields first, then the Sort field, then Range fields. For orders by customer, status, newest first and amount above 500: { customerId: 1, status: 1, createdAt: -1, amount: 1 }.
  • With the right order the results come out of the index already sorted, so there is no in-memory SORT stage.
  • explain('executionStats'): look for IXSCAN against COLLSCAN, a SORT stage, and totalKeysExamined and totalDocsExamined compared with nReturned. Numbers close together mean a good index.
  • $ne, $nin and $regex act as range conditions.
  • The same leftmost-prefix idea as in SQL applies. Multikey indexes cover arrays. Partial indexes index only some documents. A covered query reads only the index.
  • A TTL index deletes documents a set time after a date field. Use it for sessions or OTPs.
  • With $or, each clause needs its own usable index. One clause without an index can make the whole query a collection scan.
  • Build big indexes off-peak and watch replication lag. In test environments the notablescan setting makes collection scans fail loudly.

The red pen

Common traps: mistake → fix

  • Mistake: One index per field is enough

    Fix: a query with several fields needs a compound index.

  • Mistake: A SORT stage in the plan is fine

    Fix: it means the index did not give the order and memory is used.

  • Mistake: Add RAM when a query is slow

    Fix: look at the plan first.

Easy to hard

Questions interviewers ask, easy to hard

  1. What compound index would you build for: this customer, status delivered, amount above 500, newest first?
  2. What is the ESR rule?
  3. How do you read explain output?
  4. The activity feed got slow after a release that added an $or. Why?

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