NoSQL · Data models beyond tables

How do you design indexes in MongoDB?

Mediummongodbindexesquery performanceUpdated Oct 2026
Quiz this track

Short answer

Match indexes to query filters and sort order, usually with equality fields first and range or sort fields after. Use compound, multikey, unique, partial and TTL indexes deliberately and verify with explain.

MongoDB uses B-tree indexes. A compound index can serve a query only if the query uses a prefix of the index fields in a compatible order. The classic rule is equality, then sort, then range, often remembered as ESR.

js
db.orders.createIndex(
  { customerId: 1, status: 1, createdAt: -1 },
  { name: "orders_by_customer_status_date" }
);

db.orders.find({
  customerId: "cus_7",
  status: "shipped"
}).sort({ createdAt: -1 }).limit(20).explain("executionStats");
The index matches the equality fields and the sort. The explain output shows whether MongoDB used an index scan or a collection scan.

Index types and costs

  • Compound: multiple fields, supports prefix queries and combined filters
  • Multikey: indexes an array field, with one index entry per array element
  • Unique: enforces uniqueness, including on a compound key
  • Partial: indexes only documents matching a filter, saving space
  • TTL: expires documents after a time, useful for sessions and events

Every index adds write cost and memory or disk use. Do not index every field. Review slow queries, use explain to confirm index usage, and remove indexes that no query uses. A covered query, where the index contains all requested fields, avoids fetching the document.

Index build on a large collection can be expensive. Plan builds during low traffic and monitor replication lag, especially in a replica set.

Follow-ups you should expect

Interviewers use these to check whether the first answer was understanding or memorisation.

  1. 1What is the ESR rule for compound indexes?
  2. 2How does a multikey index behave with arrays?
  3. 3When would you use a partial index?
  4. 4What does a covered query mean?

Say it in the interview

I design MongoDB indexes around the actual filters and sort order, usually with equality fields first, then the sort field, then range fields. Compound indexes only help when the query uses a prefix, so field order matters. I use multikey indexes for arrays, partial indexes to save space and TTL indexes for expiring data. Every index has a write cost, so I verify usage with explain and remove indexes that no query needs.

Use this as a model, not a script. Saying it in your own words is what makes it survive follow-up pressure.

Related questions

Reading is step one

Now say it out loud.

Understanding an answer and delivering it under pressure are different skills. Rehearse this topic in a live NoSQL mock interview and get scored feedback on depth, clarity and confidence.