StackPractices
advanced By Mathias Paulenko

Complete Guide to MongoDB Indexing

Choose the right MongoDB index for every query pattern: compound, text, geospatial, TTL, wildcard, partial indexes, the ESR rule, covered queries, and explain plans.

Introduction

Your orders endpoint takes four seconds. Not always — just often enough that dashboards show a p95 tail nobody wants to own. You run .explain("executionStats") out of habit and the answer’s right there: COLLSCAN, totalDocsExamined: 2400000, nReturned: 3. The collection isn’t big by MongoDB standards; the query is just asking for it the hard way.

An index fixes that call in an afternoon. The harder part — and the part this guide is actually about — is knowing which index, because the wrong one is worse than none: every index you create slows down writes, eats RAM, and gives the query planner another way to make a surprising choice. We’ll go through each index type with runnable examples, the ESR rule for compound ordering, covered queries, Atlas Search versus the built-in text index, what indexes cost you on the write path, how to build them on a live cluster without pain, and how to read an explain plan like a mechanic reads a diagnostic report.

Examples use mongosh syntax and work on MongoDB 6.0+; driver equivalents (Mongoose, PyMongo, Java) map one-to-one. If you’re wiring models through an ODM, the MongoDB CRUD with Mongoose recipe shows the same calls in application code.

When to Index — and When Not To

Index when a query runs often enough to hurt, or when it must be fast enough that users notice: the reads your product depends on, the admin dashboard you run fifty times a day, the lookup in the hot path of every request.

Think twice before indexing when:

  • The collection is tiny. Under a few thousand documents, a collection scan is microseconds — an index adds write cost for no measurable gain.
  • The query runs weekly in a batch job. An index that exists for one cron job still taxes every write every day.
  • You’re guessing. “This field might get queried someday” produces index graveyards. Index what the workload actually does — the explain plan tells you the truth.
  • Writes dominate. Logging, telemetry, event streams: if you’re inserting far more than reading, each extra index is a tax you pay on the thing you do most.

The one-sentence version: indexes are a read optimization you pay for with writes and RAM. Buy them deliberately.

Choosing an Index: The Decision Map

Before memorizing index types, answer three questions about your query: what do you filter on, what do you sort by, and what do you return. That trio decides the shape of the index more than any index type does.

flowchart diagram: Query pattern

The single most common mistake is reaching for five separate single-field indexes when the workload needs one well-ordered compound index. We’ll see why.

Single Field Indexes

The basics first — every index below builds on these operations.

// Create a single field index
db.users.createIndex({ email: 1 });  // 1 = ascending
db.users.createIndex({ age: -1 });   // -1 = descending

// A unique index — also enforces the constraint
db.users.createIndex({ email: 1 }, { unique: true });

// List all indexes on a collection
db.users.getIndexes();

// Drop an index by name
db.users.dropIndex("email_1");

// Drop all indexes (except the mandatory _id index)
db.users.dropIndexes();

Two things worth knowing about single-field indexes before moving on:

Direction doesn’t matter for a single field. { age: 1 } and { age: -1 } serve identical queries — MongoDB walks B-tree indexes in both directions. Direction starts mattering inside compound indexes when you mix sorts.

sparse is deprecated. Older tutorials use { sparse: true } to skip documents missing the field; MongoDB 8.0 deprecated it in favor of partial indexes, which do the same thing with an explicit filter you control. If you see sparse in legacy code, migrate it — the partial version documents its intent instead of implying it.

Compound Indexes

A compound index covers several fields in one structure, and its power lives entirely in the order you list them. { status: 1, createdAt: -1 } and { createdAt: -1, status: 1 } are different indexes serving different queries.

The leading-field rule: a compound index can serve any query that filters on a prefix of its fields. { a: 1, b: 1, c: 1 } covers queries on {a}, {a, b}, and {a, b, c} — but a query filtering only on {b} or {c} falls back to a scan (or a different index). That’s why “one index per field, let the planner combine them” underperforms: index intersection is possible but the compound equivalent wins almost every time.

The ESR Rule

For the classic shape — equality filters plus a sort plus range conditions — the field order that works is Equality → Sort → Range:

// Query: active users, sorted by creation date, age >= 18
db.users.find({
  status: "active",
  age: { $gte: 18 }
}).sort({ createdAt: -1 });

// ESR order: equality first, sort second, range last
db.users.createIndex({ status: 1, createdAt: -1, age: 1 });

Why this order works. Equality fields partition the index into contiguous blocks — inside status: "active", the data for createdAt is already stored sorted, so the sort is free. The range filter on age then reads within each sorted block. Put age before createdAt and the index can still help filter, but the sort falls back to an in-memory SORT stage — bounded, and expensive at volume.

ESR is a strong default, not a law. If your range filter is extremely selective, putting it before sort sometimes wins — and when selectivity is unclear, measure both orders with explain() instead of guessing. The SQL query optimization guide covers the same trade-off from the relational side; the reasoning is identical even though the syntax isn’t.

Covered Queries

The best query is the one that never touches the collection. If every field the query filters on and returns lives inside the index, MongoDB answers directly from the index — an explain plan shows IXSCAN with no FETCH stage, and totalDocsExamined: 0.

// Index covers both the filter and the projection
db.users.createIndex({ email: 1, status: 1, lastLogin: -1 });

// Covered: filter and projected fields all live in the index
db.users.find(
  { status: "active" },
  { email: 1, lastLogin: 1, _id: 0 }   // exclude _id or it forces a FETCH
);

The _id gotcha: _id is indexed separately, so a projection that includes it breaks the cover unless your index includes _id too. Either exclude _id explicitly in the projection, or add it to the index when the shape allows.

Covered queries are how you make the hot path essentially free — the query becomes a memory-speed index walk with zero document reads. They get expensive fast if you over-include fields (the index grows), so design them for the handful of queries that run constantly.

Text Indexes — and the Atlas Search Question

MongoDB’s built-in text index tokenizes and stems field values for basic full-text search:

// One text index per collection
db.articles.createIndex(
  { title: "text", body: "text" },
  { weights: { title: 10, body: 1 }, default_language: "english" }
);

// Search with relevance scoring
db.articles.find(
  { $text: { $search: "mongodb indexing" } },
  { score: { $meta: "textScore" } }
).sort({ score: { $meta: "textScore" } });

Text indexes give you keyword matching with stemming and weights — and that’s it. No fuzzy matching, no autocomplete, no faceting, no typo tolerance, and the ranking is basic compared to a real search engine. One per collection is also a real constraint: you can’t split text indexes by document type.

If you’re on Atlas, the honest answer for anything beyond basic keyword search is Atlas Search — Lucene-backed indexes defined per collection via a separate searchIndexes API. You get analyzers, autocomplete, fuzzy search, facets, highlighting, and compound queries that combine full-text with filters:

// Atlas Search via aggregation pipeline
db.articles.aggregate([
  {
    $search: {
      index: "articles",
      compound: {
        must: [
          { autocomplete: { query: "mongo", path: "title" } },
        ],
        filter: [
          { equals: { path: "status", value: "published" } },
        ],
      },
    },
  },
]);

On self-managed deployments, the text index is your only built-in option; teams with serious search needs typically pair MongoDB with a dedicated engine (Elasticsearch, OpenSearch, Meilisearch) rather than stretching the text index past its purpose.

Geospatial Indexes

For location queries — nearest store, drivers inside a zone — MongoDB has 2dsphere (spherical, GeoJSON, what you almost always want) and 2d (flat, legacy coordinate pairs):

db.stores.createIndex({ location: "2dsphere" });

// Nearest stores within 5km of a point
db.stores.find({
  location: {
    $near: {
      $geometry: { type: "Point", coordinates: [-73.97, 40.77] },
      $maxDistance: 5000,
    },
  },
});

// Inside a polygon
db.stores.find({
  location: {
    $geoWithin: {
      $geometry: {
        type: "Polygon",
        coordinates: [[
          [-74, 40], [-73, 40], [-73, 41], [-74, 41], [-74, 40],
        ]],
      },
    },
  },
});

Geospatial indexes combine with compound indexes — put the 2dsphere field last (it’s basically the range part of ESR):

// Restaurants that are open, near me
db.restaurants.createIndex({ status: 1, location: "2dsphere" });
db.restaurants.find({
  status: "open",
  location: { $near: { $geometry: point } },
});

TTL Indexes

A TTL index deletes documents automatically once a date field ages out — session cleanup, OTP codes, audit events, temporary results:

// Delete documents 24 hours after `createdAt`
db.sessions.createIndex(
  { createdAt: 1 },
  { expireAfterSeconds: 86400 }
);

// Delete at an exact date stored in the document
db.tempResults.createIndex(
  { deleteAt: 1 },
  { expireAfterSeconds: 0 }
);

Two behaviors to know before relying on it. First, the removal isn’t instant — a background thread sweeps expired documents roughly every 60 seconds, so expired data can linger past its deadline. Never use TTL expiry as a security boundary. Second, the field must be a BSON Date (or an array containing one); a string date means the document lives forever, silently.

For time-series workloads that live or die by age, also look at time-series collections — they bucket and expire more efficiently than deleting per document.

Wildcard Indexes

When your documents carry arbitrary attributes — product catalogs where every category adds fields, user-defined custom fields — you can’t index what you can’t name. The wildcard index indexes everything it finds:

// Index all fields under attributes
db.products.createIndex({ "attributes.$**": 1 });

// Queries on any attribute now hit the index
db.products.find({ "attributes.color": "red" });
db.products.find({ "attributes.size": "XL" });

It’s genuinely useful for truly dynamic schemas — the attribute pattern is a legitimate use case. The cost is a large index (every subdocument field gets indexed) and planner behavior that’s harder to reason about than a purpose-built index. If the set of queryable fields stabilizes, named indexes usually serve the same queries with a smaller footprint.

Hashed Indexes

A hashed index stores the hash of a field’s values — distributing documents evenly across the key space. That’s almost always a sharding story: a hashed shard key prevents a monotonically increasing key (like _id or a timestamp) from funnelling every insert onto one shard.

db.users.createIndex({ _id: "hashed" });

// Equality queries work fine
db.users.find({ _id: someValue });

// Range queries don't — hash order is meaningless
db.users.find({ _id: { $gt: someValue } });  // can't use the hash

The trade-off is explicit: perfect distribution, useless ranges. The database sharding guide covers shard-key selection end to end — hashed keys are one option in a bigger decision.

Partial Indexes

A partial index only indexes documents matching a filter — smaller, faster to maintain, and expressive about intent:

// Index only active users — the inactive majority doesn't pay index cost
db.users.createIndex(
  { email: 1 },
  { partialFilterExpression: { status: "active" } }
);

// Works for queries whose filter implies the partial predicate
db.users.find({ status: "active", email: "a@b.com" });   // uses it
db.users.find({ email: "a@b.com" });                     // doesn't — can't guarantee status

The subtlety that bites people: the query must guarantee the index’s predicate, not just match it by accident. partialFilterExpression: { status: "active" } won’t serve a query that doesn’t constrain status — the planner can’t prove the missing documents are safe to skip.

Partial indexes are the modern answer to the deprecated sparse option: { partialFilterExpression: { field: { $exists: true } } } reproduces sparse semantics with explicit intent.

Index Intersection

MongoDB can combine several single-field indexes for an AND query — { status: 1 } plus { age: 1 } can answer { status: "active", age: { $gt: 18 } } by intersecting key sets. It works, and occasionally it’s the pragmatic choice when a compound index doesn’t exist yet and you can’t afford a build today.

But measure before relying on it: intersection reads several index structures and merges, while the equivalent compound index reads one contiguous range. For query shapes your workload uses constantly, build the compound index and let intersection handle the incidental cases. For OR queries it’s the opposite — $or clauses use index intersection naturally across the branches.

The Write Cost of Indexes

Every index you create is a promise to maintain it. On every insert and every update touching an indexed field, MongoDB writes the document and updates every applicable index — ten indexes means ten maintenance writes per mutation. On insert-heavy workloads that cost is real throughput.

Two less obvious taxes:

  • RAM pressure. Indexes want to live in the WiredTiger cache alongside the working set. Every index you keep resident is memory your hottest documents can’t use — and index pages falling out of cache turn cheap queries into disk reads.
  • Lock and I/O on builds. Index builds on a large collection are heavy; on production primaries they can degrade the cluster while running. Modern builds (4.2+) are far better than the old background: true era, but “far better” isn’t free.

The practical rule: index count on a hot collection stays small enough to fit in RAM and cheap enough for your write rate. Audit the indexes you’ve got before adding the next one — db.collection.aggregate([{ $indexStats: {} }]) shows which ones are actually being used.

Indexes in Production

Building and dropping indexes on a live cluster deserves its own checklist:

// See which indexes get used (and how much)
db.users.aggregate([{ $indexStats: {} }]);

// Test a drop safely — hide the index instead of deleting it
db.users.hideIndex("status_1");
// ... observe the workload; if queries degrade, bring it back instantly
db.users.unhideIndex("status_1");

// Force a specific index when diagnosing plan choices
db.users.find({ status: "active" }).hint({ status: 1 });
  • Hide before you drop. hideIndex makes an index invisible to the planner while keeping it maintained — if latency spikes you restore it in one command instead of rebuilding for an hour.
  • On large replica sets, consider rolling builds. Take a secondary out, build the index standalone, rejoin and repeat — the cluster never feels the build. Atlas automates rolling builds; on self-managed you orchestrate it.
  • Check Atlas’s Index Advisor if you’re on Atlas — it watches your workload and suggests indexes from real query patterns, which beats guessing from the schema.
  • New indexes can change plans for existing queries. A better option appearing is usually good, but occasionally the planner picks the new index for a query it serves worse — that’s what hideIndex and hint are for when you need control.

Explain Plan Analysis

Everything above converges here: .explain("executionStats") is how you verify the index does what you think it does.

db.users.find({ status: "active", age: { $gt: 18 } })
  .explain("executionStats");

The fields that tell the story:

FieldWhat it says
winningPlan.stageCOLLSCAN = full scan, IXSCAN = index, FETCH = doc reads, SORT = in-memory sort
totalKeysExaminedIndex entries walked — should be close to matches
totalDocsExaminedDocuments read — should be ≈ nReturned
nReturnedDocuments returned
executionTimeMillisWall-clock execution time

The ratios matter more than the absolute numbers:

// Healthy: 1 doc examined per doc returned — index did the filtering
// totalKeysExamined ≈ totalDocsExamined ≈ nReturned

// Wasteful: scanning a million docs to return three
// totalDocsExamined: 1000000, nReturned: 3  → missing index

// Sorting in memory: stage SORT appears instead of free index order
// → index field order wrong for the sort, or range before sort in ESR

A FETCH after IXSCAN isn’t a problem — it means the index found candidates and MongoDB read the documents; it’s only “uncovered.” A FETCH missing entirely is your covered-query win. And a SORT stage on a big result set is the planner telling you the index order doesn’t match your sort — revisit ESR.

Index Maintenance

Indexes drift out of usefulness as workloads change. A quick maintenance habit:

// What indexes exist and how big they are
db.users.getIndexes();
db.users.stats().indexSizes;

// Which ones actually serve queries
db.users.aggregate([{ $indexStats: {} }]);

Review quarterly: drop or hide indexes with near-zero ops in $indexStats, check that the indexes answering your hottest queries are still the right ones, and watch indexSizes creep as data grows. Index hygiene is also a security issue of sorts — a bloated index working set squeezes out memory that the whole database shares.

What Works

  • Design from the query log, not the schema. Pull your slow-query log or profiler output, list the top query shapes, and index those. Schema-driven indexing guesses wrong.
  • One good compound index beats five single ones for the queries that matter — prefix coverage does the rest.
  • Covered queries on the hot path. The three queries that run 80% of your reads deserve indexes they never leave.
  • Hide, don’t drop. $indexStats plus hideIndex lets you prove an index is dead weight before removing it — reversible beats confident.
  • Budget indexes like memory. Every one you add costs write throughput and cache space; the cap is a number, not a feeling.

Common Mistakes

  • Compound fields in the wrong order. Equality-then-range-then-sort means your sort ran in memory; ESR exists because order is the whole point.
  • Indexing “just in case.” Unused indexes aren’t neutral — they tax every write and every rebuild.
  • Expecting partial indexes on a non-guaranteeing query. The planner only uses the partial index when your query implies its predicate.
  • Relying on TTL for hard expiry. The sweeper runs on its own schedule; documents can outlive their deadline by a minute or more.
  • Treating text as a search engine. For fuzzy, autocomplete, or faceted search you want Atlas Search or a dedicated engine — text is keyword matching, full stop.
  • Leaving _id in covered-query projections. It silently breaks the cover and adds the FETCH you meant to avoid.
  • Building indexes on a busy primary during traffic. Rolling builds or off-peak windows exist for a reason.

See Also

Frequently Asked Questions

How many indexes should I create?

As few as serve your real queries — there's no magic number, but a collection with ten+ indexes is usually carrying dead weight. Start with your slow-query log, index the hot paths, and let $indexStats tell you quarterly which ones earn their keep.

What is the ESR rule and why does it matter?

Equality → Sort → Range: order compound index fields so equality filters come first, the sort field second, and range filters last. Ordered that way, the index serves the filter and the sort for free; ordered wrong, you get the index helping with the filter while the sort runs in memory — visible as a SORT stage in explain.

When should I use a compound index vs multiple single indexes?

Almost always compound for a query you run often — it reads one contiguous index range where intersection merges several. Several singles only make sense when each field is queried alone, or for $or shapes where the planner intersects across branches naturally.

What's the difference between sparse and partial indexes?

sparse skipped documents lacking the field — it's deprecated as of MongoDB 8.0. Partial indexes do the same job explicitly: { partialFilterExpression: { field: { $exists: true } } }, or any richer predicate. New work should use partial.

How do I know if my query is using an index?

.explain("executionStats") — look for IXSCAN in the winning plan, totalDocsExamined close to nReturned, and no unbounded SORT stage. COLLSCAN means no usable index; totalDocsExamined in the millions against a handful of results means the index exists but isn't serving this query.

Can I index arrays in MongoDB?

Yes — a field containing arrays becomes a multikey index automatically, with one index entry per array element. One rule to remember: a compound index can be multikey on at most one array field, so { tags: 1, categories: 1 } fails if both are arrays.

Do indexes slow down writes?

Yes — each insert and each update on indexed fields must maintain every applicable index. On read-heavy workloads it's a bargain; on write-heavy streams, keep index count deliberately low.

Should I use the text index or Atlas Search?

For basic keyword search on self-managed MongoDB, text works. For fuzzy matching, autocomplete, faceting, or relevance tuning, Atlas Search (Lucene-backed) or a dedicated search engine is the right tool — text can't grow into those requirements.