Databases & Data Access
Node.js MongoDB Indexes and Query Performance
An index is a sorted structure that lets MongoDB find matching documents without scanning the whole collection. Without one, every query reads every document — fine at a thousand records, fatal at a million.
What is MongoDB Indexes and Query Performance in Node.js?
An index is a sorted structure that lets MongoDB find matching documents without scanning the whole collection. Without one, every query reads every document — fine at a thousand records, fatal at a million.
Why MongoDB Indexes and Query Performance matters
Slow API endpoints are usually missing indexes rather than slow code. A query that scans 400,000 documents takes seconds; the same query on an index takes milliseconds.
MongoDB Indexes and Query Performance example
// explain shows what actually happened
const plan = await Job.find({ city: 'Pune', status: 'active' })
.sort({ createdAt: -1 })
.explain('executionStats');
console.log(plan.executionStats.totalDocsExamined); // want ≈ nReturned
console.log(plan.queryPlanner.winningPlan.stage); // COLLSCAN is bad, IXSCAN is good
// a compound index matching filter + sort
jobSchema.index({ city: 1, status: 1, createdAt: -1 });Key points to remember
- Compound index order matters: equality fields first, then sort fields.
- COLLSCAN in an explain plan means no usable index exists.
- Indexes speed reads and slow writes — index deliberately, not exhaustively.
- Build indexes in the background on a live production collection.
Index types
| Type | For |
|---|---|
| single field | one filter field |
| compound | multiple filters, and sorting |
| text | full-text search across string fields |
| unique | enforcing no duplicates, such as email |
| TTL | auto-expiring documents like OTPs and sessions |
Common mistakes with MongoDB Indexes and Query Performance
- A case-insensitive regular expression without a leading anchor, which cannot use an index.
- Sorting on a field absent from the index used for filtering, forcing an in-memory sort.
Node.js MongoDB Indexes and Query Performance— Interview Questions & FAQs
How do I know if my MongoDB query is slow?+
Run .explain("executionStats") and compare totalDocsExamined with nReturned. If it examined far more documents than it returned, or the winning plan is COLLSCAN, you need an index.
