Ch. 12 · MongoDB

MongoDB Compound Indexes and Query Order

MongoDB Compound Indexes and Query Order. Learn the reasoning, a practical example, common mistakes and an interview exercise.

~2 min readbeginnerupdated Oct 3, 2026

Compound indexes order keys and serve particular filters and sorts. Design from real query shapes rather than adding every field.

Before you start

You should understand documents, collections and indexes. Sketch representative documents and the reads and writes they must support. MongoDB-specific examples assume a collection with the shown fields; deployment topology, permissions and existing indexes can affect the operational behavior being discussed.

The practical goal is to reason through this situation: A tenant-filtered listing sorted by date benefits from an index aligned with those operations. Read the walkthrough first, then try the interview exercise before opening its answer. The important part is explaining the decision and its consequences, rather than remembering a definition alone.

Step-by-step walkthrough

Step 1: Capture the query shape

Record equality filters, sorting and ranges.

Step 2: Propose ordered keys

Align tenant filtering and requested date order under the real workload.

Step 3: Inspect actual plans

Verify examined counts and sorting rather than inferring benefit from index existence.

Worked scenario

A tenant-filtered listing sorted by date benefits from an index aligned with those operations.

A tenant listing orders by createdAt and _id. An index beginning with tenant and matching the sort is a candidate, but range predicates or different sort direction combinations can change usability. The same index is not automatically appropriate for cross-tenant reporting.

Common mistake

An index’s existence does not prove the query can avoid sorting or scanning.

Verify the behavior

Run explain on real filters and sort forms with representative distributions.

Interview exercise

Validate an index proposal.

Answer and reasoning

Inspect explain output on representative data and account for equality, sort and range behavior.

Continue learning

Compare the scenario with the MongoDB interview questions and test your understanding with the MongoDB MCQs. For terminology and implementation details, consult the reference material.

More in MongoDB

read ✓MongoDB · mid

MongoDB Bulk Writes

Batch inserts and updates with bulkWrite, choose ordered or unordered, and handle partial failures correctly.

~2 min readread →
read ✓MongoDB · mid

MongoDB Capped Collections

Use capped collections for fixed-size, insertion-ordered logs, and know why documents cannot grow.

~2 min readread →
read ✓MongoDB · hard

MongoDB Change Streams and Resume Tokens

React to inserts and updates with change streams, persist resume tokens, and handle invalidate and failover correctly.

~2 min readread →
esc