Lesson 12 / 22

Indexes

Speed up queries by avoiding a full collection scan.

Why indexes matter

Without an index, MongoDB scans every document to find matches. An index is a sorted structure that lets it jump straight to the right documents.

Creating an index

1 means ascending order, -1 means descending.

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

Checking the query plan

explain() shows whether a query used an index scan (IXSCAN) or a slower collection scan (COLLSCAN).

db.users.find({ email: "ada@example.com" }).explain("executionStats")

Indexes aren't free

Each index speeds up reads but slows down writes slightly and uses extra storage — index only the fields you actually query on.