Introduction to Indexes
Understand why indexes exist, create your first index, and see the dramatic performance difference they make.
The Problem: Collection Scans
Without an index, MongoDB must perform a collection scan — examining every single document to find ones matching a query. On a collection with a few dozen documents this is invisible; on one with millions, it becomes painfully slow.
What an Index Does
An index is a separate, ordered data structure that maps field values to document locations — conceptually similar to a book's index letting you jump straight to a topic instead of reading every page. It lets MongoDB find matching documents directly, without scanning the whole collection.
Creating a Single-Field Index
db.users.createIndex({ email: 1 }); // 1 = ascending orderOnce created, a query filtering on email can use this index to jump directly to matching documents instead of scanning the whole collection.
db.users.find({ email: "ada@example.com" }); // now uses the index automaticallyThe Default _id Index
Every collection automatically gets a unique index on _id when it's created — this is why looking up a document by its _id is always fast, with no extra setup required.
Unique Indexes
Passing { unique: true } enforces that no two documents can share the same value for the indexed field — the standard way to guarantee something like email addresses are never duplicated.
db.users.createIndex({ email: 1 }, { unique: true });Every index speeds up matching reads, but also adds overhead to every write (since the index must be updated too) and consumes additional storage — indexes should be added deliberately, matched to real query patterns, not applied to every field by default.
Common Beginner Mistakes
Each unnecessary index slows down writes and wastes storage without a matching read benefit — create indexes based on actual, known query patterns.
A unique index is a strong database-level safety net, but your application should still handle the resulting error gracefully (e.g. "this email is already registered") rather than crashing.
FAQs
Up to 64 per collection — in practice, most well-designed collections need far fewer, matched to their actual query patterns.
Not necessarily — building an index on an existing large collection can take significant time; MongoDB supports building indexes in the background to avoid blocking other operations.
Summary
An index lets MongoDB jump directly to matching documents instead of scanning an entire collection, at the cost of some write overhead and storage. Next, you'll learn compound indexes, covering queries that filter on multiple fields at once.