All academies
Roadmap
LEVEL 6 · INDEXES

How Indexes Work

12 min read

Without an index, MongoDB performs a collection scan (COLLSCAN) — it reads every document. An index is a B-tree of sorted key values with pointers to documents, so lookups become tree traversals: O(log n) instead of O(n).

Creating indexes

createIndex takes a key pattern: 1 ascending, -1 descending. Direction matters only for compound sorts.

mongosh
db.users.createIndex({ email: 1 }, { unique: true })
db.products.createIndex({ category: 1, price: -1 })
db.products.getIndexes()

Reading explain()

Append .explain() to see the plan. IXSCAN = index used; COLLSCAN = full scan. Compare totalDocsExamined to nReturned: a big gap means wasted work. Try this live in the index visualizer.

mongosh
db.products.find({ category: "electronics" }).explain()
// winningPlan.stage: "IXSCAN", indexName: "category_1"

The cost of indexes

Every index slows down writes (each insert/update must also update the B-tree) and consumes RAM. Index what you query — and nothing more.

Try it yourself

db.products.find({ category: "electronics" }).explain()
Run in Shell

Check your understanding

Q1.

What plan stage indicates a full collection scan?

Q2.

explain() shows totalDocsExamined: 10000, nReturned: 3. What does this suggest?

code
db.orders.find({ email: 'a@b.com' }).explain()
Q3.

Adding more indexes always makes your application faster.