Skip to content

Lesson 4 of 9 · 28m

Indexes Are Query Shapes, Not Decoration

Read explain output, understand compound key order, and design indexes around equality, sort, range, and selectivity instead of adding indexes reactively.

Every overloaded MongoDB system I have been called into had indexes. Usually too many. Usually in the wrong order. Usually created after someone ran a profiler for ten minutes and treated the output like a shopping list. Indexes are not decorations you sprinkle on slow queries; they are physical access paths designed for specific query shapes.

Start with explain, not vibes

Run the real query through explain:

db.orders.find(
  { customerId: ObjectId("665f1c22bfd34cf7b2785c80"), status: "shipped" }
).sort({ createdAt: -1 }).limit(20).explain("executionStats")

Read executionStats like a practitioner:

stage              what you want
COLLSCAN           usually bad on a hot collection
IXSCAN             index scan, but inspect keys examined
FETCH              documents loaded after index filtering
SORT               in-memory sort unless index order satisfies it
nReturned          rows returned to client
totalKeysExamined  index entries inspected
totalDocsExamined  documents loaded

A good query examines close to the number of documents it returns. Huge gaps mean the index is helping only marginally or the filter is not selective.

Compound index order is ESR

A practical ordering mnemonic is Equality, Sort, Range:

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

This serves equality on customerId and status, then uses createdAt order for sorting. It also serves prefixes: {customerId} and {customerId,status}. It does not efficiently serve a query only on status because index scans start at the leftmost fields.

// good match
db.orders.find({ customerId: c, status: "shipped" }).sort({ createdAt: -1 })
// poor match for this index alone
db.orders.find({ status: "shipped" }).sort({ createdAt: -1 })

Index order is not commutative. {a:1,b:1} and {b:1,a:1} are different access paths.

Covered queries are powerful but easy to overrate

A covered query can answer entirely from the index:

db.orders.find(
  { customerId: c, status: "shipped" },
  { _id: 0, customerId: 1, status: 1, createdAt: 1 }
).sort({ createdAt: -1 })

If the projection contains only indexed fields, MongoDB may avoid fetching documents. This is excellent for hot list endpoints. But do not contort every document into narrow key-value pairs just to chase coverage; duplication and update complexity become their own tax.

Indexes cost writes and memory

Every index is updated on inserts and relevant updates. A collection with twelve indexes can turn a simple write into a small ceremony. Inspect usage before adding more:

db.orders.aggregate([{ $indexStats: {} }])

Drop unused duplicate-prefix indexes, but first verify that rare operational jobs do not depend on them. An index can be cold in the application yet critical for a monthly reconciliation process.

Field notes

  • Regex queries can use indexes only in narrow anchored cases; /^abc/ is very different from /abc/.
  • Multikey indexes over arrays complicate compound index behavior and can explode index size.
  • Partial indexes are excellent for hot subsets such as status: "active" when most rows are inactive.
  • If explain shows a large in-memory SORT, either the index order is wrong or the query is asking for a report on a hot path.

Was this lesson helpful?

Sign in to rate