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

Indexes in MongoDB

Creating and using indexes on document fields to speed up queries, including single-field and compound indexes.

Indexes in MongoDB

You'll learn how MongoDB uses indexes to speed up queries on document fields without scanning entire collections.

What Are Indexes?

An index is like a book's index at the back—instead of reading every page to find "MongoDB," you look it up in the alphabetical index and jump straight to the relevant pages. In MongoDB, indexes create sorted data structures that point to documents, allowing queries to find matches in milliseconds instead of scanning millions of documents.

Without an index, MongoDB performs a collection scan, examining every document to find matches. With an index on the queried field, MongoDB jumps directly to the relevant documents.

Creating Indexes in MongoDB

MongoDB automatically creates an index on the _id field (the ObjectId primary key you learned about). You can create additional indexes on any field:

db.users.createIndex({ email: 1 })

The 1 means ascending order. This index makes queries like db.users.find({ email: "alice@example.com" }) extremely fast.

Compound Indexes

You can index multiple fields together for queries that filter on several criteria:

db.orders.createIndex({ customerId: 1, orderDate: -1 })

This compound index optimizes queries filtering by customerId and sorting by orderDate (descending, indicated by -1). Field order matters—this index helps queries starting with customerId, but not queries on orderDate alone.

The Trade-off

Indexes speed up reads but slow down writes—every insert or update must also update the indexes. Choose indexes based on your most frequent query patterns.

Key Takeaway: Indexes in MongoDB dramatically accelerate queries by creating sorted lookups on document fields, with single-field indexes for simple queries and compound indexes for multi-field filtering and sorting.