A Practical Guide to MongoDB Indexing

A Practical Guide to MongoDB Indexing

Compound indexes, the ESR rule and reading explain() output, so your queries stop scanning whole collections.

Most slow MongoDB apps do not need a bigger cluster. They need the right indexes. Here is how I design them.

Start from real queries

Enable the profiler or check Atlas Performance Advisor to see which queries are slow and how often they run. Index for the hot paths, not every field.

The ESR rule for compound indexes

  1. Equality fields first, such as status or userId.
  2. Sort fields next, such as createdAt.
  3. Range fields last, such as price greater than a value.
// Query: active listings in a category, newest first, under a price
db.listings.createIndex({ status: 1, category: 1, createdAt: -1, price: 1 });

Covered queries

If the index contains every field the query filters on and returns, MongoDB can answer from the index alone. Projecting only indexed fields on list endpoints is a cheap, large win.

Read explain()

  • IXSCAN is good, COLLSCAN on a large collection is not.
  • Compare totalDocsExamined with nReturned. Close numbers mean a selective index.
  • A SORT stage means the sort is in memory; adjust the index order.

Indexes are not free

Every index slows writes and uses memory. Remove unused ones; Atlas and $indexStats show how often each index is used.

More on this topic

Photography
3D Models
Development
Illustrations
Fashion
Digital Art
Packaging
Motion
Illustrations
Video Production
Photography
3D Models
Development
Illustrations
Fashion