MyInternships.in

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

Diagnosing and fixing
JavaScript
// 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

TypeFor
single fieldone filter field
compoundmultiple filters, and sorting
textfull-text search across string fields
uniqueenforcing no duplicates, such as email
TTLauto-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.

Related Node.js Topics

Keep learning with these closely related lessons.

Ready to use your Node.js skills?

Find verified Node.js internships and fresher developer jobs across India.

Browse Node.js Internships