How does indexing work in MongoDB and what types of indexes exist?
Learn how MongoDB indexing works and every index type — single, compound, multikey, text, TTL and more — with code and interview-ready explanations.
Expected Interview Answer
A MongoDB index is a B-tree data structure that stores the values of one or more fields in sorted order with pointers to the source documents, letting queries jump straight to matching records instead of scanning every document in the collection.
Without an index, MongoDB performs a collection scan, examining every document to satisfy a query, which is slow at scale. An index lets the query planner seek and range-scan sorted keys, dramatically cutting the documents examined. MongoDB supports single-field, compound, multikey (arrays), text, geospatial (2d/2dsphere), hashed, wildcard, and TTL indexes, plus modifiers like unique, partial, and sparse. Every collection has a default unique index on _id.
- Turns full collection scans into fast seeks
- Supports efficient sorting without an in-memory sort
- Enforces uniqueness with unique indexes
- Enables specialized queries (text search, geospatial, TTL expiry)
- Covered queries can be answered from the index alone
- Reduces documents examined, lowering CPU and I/O
AI Mentor Explanation
A cricket statistician who wants every wicket taken by one bowler could replay all match footage ball by ball, or open a pre-sorted bowler-wise wicket register and flip straight to that name. A MongoDB index is that register: field values kept in sorted order with pointers, so the query seeks the bowler instead of scanning every delivery.
Step-by-Step Explanation
Step 1
Create the index
Use createIndex on the fields you filter or sort by, choosing ascending (1) or descending (-1) order for each field.
Step 2
Query planner picks it
When a query runs, the planner evaluates candidate indexes and caches a winning plan that seeks the B-tree instead of scanning.
Step 3
Seek and range-scan
The engine navigates the sorted keys to the first match and walks the range, following pointers to fetch matching documents.
Step 4
Cover when possible
If all needed fields live in the index, MongoDB returns results directly from the index (a covered query) with no document fetch.
Step 5
Verify with explain
Run explain('executionStats') and check for IXSCAN over COLLSCAN, and that totalDocsExamined is close to nReturned.
What Interviewer Expects
- Knows an index is a sorted B-tree with pointers, not a copy of the data
- Can name several index types and when to use each
- Understands compound index field order and the ESR rule
- Distinguishes IXSCAN from COLLSCAN via explain
- Aware of trade-offs: faster reads but slower writes and extra storage
Common Mistakes
- Thinking more indexes are always better, ignoring write and storage cost
- Getting compound index field order wrong so the index cannot be used
- Confusing multikey (array) indexes with compound indexes
- Forgetting the default _id index already exists
- Not using explain to confirm the index is actually chosen
Best Answer (HR Friendly)
“An index in MongoDB is like the index at the back of a book: instead of reading every page to find a topic, you look it up in a sorted list that points straight to the right page. MongoDB offers several kinds for different needs, such as text search, location data, and auto-expiring records, which makes queries much faster.”
Code Example
// Single-field index, ascending
db.users.createIndex({ email: 1 }, { unique: true })
// Compound index (order matters: Equality, Sort, Range)
db.orders.createIndex({ status: 1, createdAt: -1 })
// Multikey index (automatic on an array field)
db.posts.createIndex({ tags: 1 })
// Text index for full-text search
db.articles.createIndex({ title: 'text', body: 'text' })
// TTL index: documents expire 3600s after createdAt
db.sessions.createIndex({ createdAt: 1 }, { expireAfterSeconds: 3600 })
// Partial index: only index active accounts
db.accounts.createIndex(
{ lastLogin: 1 },
{ partialFilterExpression: { active: true } }
)db.orders
.find({ status: 'shipped' })
.sort({ createdAt: -1 })
.explain('executionStats')
// Look for winningPlan.stage === 'IXSCAN'
// and executionStats.totalDocsExamined close to nReturnedFollow-up Questions
- What is the ESR (Equality, Sort, Range) rule for ordering compound index fields?
- How does a covered query differ from an ordinary indexed query?
- What are the downsides of having too many indexes on a collection?
- How does a multikey index behave on an array field?
- When would you choose a hashed index over a range index?
MCQ Practice
1. What underlying data structure does a standard MongoDB index use?
Standard MongoDB indexes are B-trees, which keep keys sorted and support efficient equality and range lookups.
2. Which index type automatically expires documents after a set time?
A TTL index uses expireAfterSeconds to have MongoDB delete documents once a date field ages past the threshold.
3. In explain output, which stage indicates an index was used instead of a full scan?
IXSCAN means the query traversed an index; COLLSCAN means every document was examined.
Flash Cards
What is the default index on every collection? — A unique index on the _id field, created automatically and cannot be dropped.
What is a covered query? — A query whose fields are all present in an index, so MongoDB returns results from the index without fetching documents.
What is a multikey index? — An index on a field holding an array; MongoDB creates an index key for each array element.
What is the ESR rule? — Order compound index fields as Equality, then Sort, then Range for best efficiency.