← Lessons

quiz vs the machine

Gold1340

Databases

The MongoDB Indexes

How indexes turn full collection scans into fast lookups.

5 min read · core · beat Gold to climb

Why Indexes Exist

Without an index a query must perform a collection scan, reading every document to find matches. An index is a sorted B tree structure on one or more fields that lets the engine jump straight to matching documents.

How They Work

  • Each index entry stores the indexed field value and a pointer to the document.
  • Because entries are sorted, the engine can do range scans and ordered reads cheaply.
  • Every collection has an automatic index on the underscore id field.

Costs to Weigh

  • Indexes consume storage and must be updated on every insert, update, and delete.
  • Too many indexes slow writes and waste memory in the working set.
  • An index only helps if the query can use its leading fields.

Use the explain output to confirm a query uses an index. Look for an index scan stage rather than a collection scan, and watch that the number of documents examined stays close to the number returned.

Key idea

A MongoDB index is a sorted B tree on chosen fields that replaces full collection scans with direct lookups, at the cost of extra storage and slower writes.

Check yourself

Answer to earn rating on the learn ladder.

1. What happens when a query has no usable index?

2. What is a cost of adding more indexes?