Course contentsShow
← System Design
Lesson 385 of 1,91911. NoSQL: Document StoresFree lesson

Indexing in Document Stores

Indexes on document fields accelerate queries; compound and multi-key indexes support complex query patterns.

Indexing in Document Stores

What you'll learn: How indexes on document fields dramatically speed up queries and enable complex search patterns in document stores.

The Problem Without Indexes

By default, when you query documents by a field (as we learned previously), the database must scan every document in the collection to find matches. Imagine searching for all users with age: 25 in a collection of 10 million documents—without an index, the database reads all 10 million documents sequentially.

What Indexes Do

An index is like the index at the back of a textbook. Instead of reading every page to find mentions of "databases," you look up "databases" in the index and jump directly to the relevant pages.

In document stores, you create indexes on frequently queried fields. When you index the age field, the database builds a sorted data structure mapping each age value to the documents containing it. Now that search for age: 25 becomes nearly instant.

Types of Indexes

Single-field indexes accelerate queries on one field: indexing email speeds up lookups by email address.

Compound indexes cover multiple fields together, like indexing (country, city) to efficiently query "all users in Paris, France."

Multi-key indexes handle array fields. If a document has tags: ["javascript", "react"], a multi-key index on tags creates index entries for both values, letting you quickly find all documents tagged with "react."

The Trade-off

Indexes consume storage and slow down writes (the database must update indexes whenever documents change), but they transform slow queries into fast ones.

Key Takeaway: Indexes on document fields turn full collection scans into targeted lookups, with compound and multi-key indexes supporting complex query patterns at the cost of write overhead and storage.