Learn to Code
All tracks
Learn to Code

Free lessons from scratch to pro — every language, databases and DevOps.

AboutContactPrivacy PolicyTerms of Use

Your progress is saved in this browser. © 2026 Learn to Code

MDB
MongoDB
0/10 completed
Beginner
What is MongoDB?Inserting and finding documentsUpdating and deleting
Intermediate
Query operatorsSorting, paging and projectionIndexes and explain()
Advanced
The aggregation pipelineJoins, facets and window functionsSchema design and validation
Pro
Drivers, transactions and scaling
Tracks / MongoDB / Intermediate

Indexes and explain()

With 10 documents, every query is instant. With 10 million, a query without the right index reads every document on disk: a collection scan. Indexes are the single biggest factor in MongoDB performance.

How an index helps

An index is a sorted list of one or more field values, each pointing to its document. To find email: 'x', MongoDB walks the sorted index (a B-tree) in a few steps instead of reading the whole collection. Every collection has an index on _id automatically.

The cost: indexes use memory and disk, and every write must update them. So you create the indexes your queries need, not one per field.

Seeing the plan with explain()

explain('executionStats') shows how MongoDB ran a query. Look at three things:

  • winningPlan.stage: COLLSCAN (read everything) or IXSCAN (used an index)
  • totalDocsExamined vs nReturned: ideally close to each other
  • totalKeysExamined: index entries read
MongoDB shell (simulated) · editable

A COLLSCAN that examined 8 documents to return 2. Now create an index and run the same query:

MongoDB shell (simulated) · editable

Now it's an IXSCAN that examined exactly the 2 documents it returned.

The editor's planner is a simplified simulation of MongoDB's, so it's great for learning to read plans. On a real server, explain() returns many more details.

Creating and managing indexes

MongoDB shell (simulated) · editable

Unique indexes

A unique index rejects duplicates, which is how you enforce "one account per email":

MongoDB shell (simulated) · editable

Missing fields count as null, so a second user without an email also clashes. If the field is optional, use a partial index that only covers documents that have it:

MongoDB shell (simulated) · editable

Compound indexes and the ESR rule

A compound index covers several fields, like { status: 1, createdAt: -1 }. It's sorted by the first field, then by the second within each value of the first.

Field order matters. MongoDB's guideline is ESR:

  1. Equality fields first (status: 'shipped')
  2. Sort fields next (sort({ createdAt: -1 }))
  3. Range fields last (total: { $gt: 100 })
MongoDB shell (simulated) · editable

Equality on status, then results come out of the index already sorted by createdAt, so there's no in-memory SORT stage. Compare a sort the index can't help with:

MongoDB shell (simulated) · editable

A compound index also serves queries on its prefix: { status: 1, createdAt: -1 } helps queries on status alone, but not on createdAt alone.

Covered queries

If the filter and the returned fields are all in the index, MongoDB answers from the index without reading any documents. That's a covered query, the fastest kind:

MongoDB shell (simulated) · editable

totalDocsExamined: 0. (You must exclude _id, since it isn't in that index.)

Special index types

Type Use
Multikey Created automatically when you index an array field: one entry per element
Text Basic word search: createIndex({ title: 'text' }) and $text queries
TTL Deletes documents automatically after a time: { expireAfterSeconds: 3600 } on a date field. Great for sessions and logs.
2dsphere Geospatial: "restaurants within 2 km"
Hashed Even distribution for sharding
Wildcard Indexes unknown or varying field names: { 'attributes.$**': 1 }
js
// Sessions disappear 1 hour after createdAt (a real server's background job deletes them)
db.sessions.createIndex({ createdAt: 1 }, { expireAfterSeconds: 3600 })

On MongoDB Atlas, Atlas Search and Vector Search indexes add full-text search and AI similarity search.

Index strategy in practice

  • Index the fields your frequent queries filter and sort on; check them with explain().
  • Prefer one good compound index (following ESR) over several single-field ones.
  • Remove unused indexes: on a real server, db.collection.aggregate([{ $indexStats: {} }]) shows how often each is used.
  • Keep your working set (hot data plus indexes) in RAM.
  • Atlas's Performance Advisor suggests indexes based on slow queries.

Practice

  1. Run explain('executionStats') on db.products.find({ category: 'Electronics', price: { $lt: 100 } }).
  2. Create the best compound index for it (think ESR), and run explain again.
  3. Make sku a unique field in a new inventory collection, and prove it rejects duplicates.
MongoDB shell (simulated) · editable
✎ Check your understanding

1.In explain output, what does COLLSCAN mean?

2.Following ESR, which index suits find({ status: 'paid', total: { $gt: 50 } }).sort({ createdAt: -1 })?

3.Why might a unique index on email reject a second user who has no email at all?

← Sorting, paging and projection