█
LastWrite
  • > Curriculum
  • > Pricing
  • > For Educators
  • > About
  • > Contact
Log InGet Started

Questions, concerns, bug reports, or suggestions? We read every message, write to us at [email protected].

More ways to reach us →
LastWrite

Structured computer science lessons for aspiring developers and security professionals.

[email protected]

(201) 785-7951

Mon–Fri, 9 AM–5 PM EST

Learn

  • Curriculum
  • Pricing

Company

  • About
  • For Educators & Schools
  • Contact Us

Legal

  • Terms of Service
  • Privacy Policy
© 2026 LastWrite. All rights reserved.
Curriculum/Programming Languages/MongoDB/Indexing in MongoDB
50 minIntermediate

Indexing in MongoDB

After this lesson, you will be able to: Create single-field, compound, text indexes; use explain() to verify queries hit indexes.

Same B-tree idea as SQL indexes; same write-cost trade-off. The Mongo flavor adds compound key direction + text indexes + geospatial.

Prerequisites:Aggregation Pipeline

Index basics

Mongo always indexes _id. You add the rest.

css
// Single-field
db.users.createIndex({ email: 1 }, { unique: true }); // 1 = asc, -1 = desc
// Compound
db.users.createIndex({ age: 1, lastLoginAt: -1 });
// Partial (only indexes matching docs, smaller, faster)
db.users.createIndex(
{ email: 1 },
{ partialFilterExpression: { active: true } }
);
// TTL, auto-delete after a time (great for sessions / OTP codes)
db.sessions.createIndex({ createdAt: 1 }, { expireAfterSeconds: 3600 });
// List indexes
db.users.getIndexes();
// Drop
db.users.dropIndex({ email: 1 });

Verify queries use indexes

explain('executionStats').

tsx
db.users.find({ email: "[email protected]" }).explain("executionStats");
// Key fields in output:
// winningPlan.stage === "IXSCAN" → index used
// winningPlan.stage === "COLLSCAN" → collection scan (bad)
// executionStats.executionTimeMillis
// executionStats.totalKeysExamined / totalDocsExamined / nReturned
//
// Ideal ratio: totalKeysExamined ≈ nReturned (low fanout)

Compound index direction

Direction matters for sorts.

tsx
// Index: { age: 1, joinedAt: -1 }
// Uses index:
db.users.find({}).sort({ age: 1, joinedAt: -1 });
db.users.find({}).sort({ age: -1, joinedAt: 1 }); // exact reverse
db.users.find({ age: 30 }).sort({ joinedAt: -1 });
// Does NOT use index for sort:
db.users.find({}).sort({ age: 1, joinedAt: 1 }); // direction mismatch
db.users.find({}).sort({ joinedAt: -1 }); // skips prefix (age)
// Same leftmost-prefix rule as SQL, but ALSO direction must match (or be exact reverse).

💡 Text + geospatial indexes

Text: `db.posts.createIndex({ title: 'text', body: 'text' })` enables `$text: { $search: ... }`. Geospatial: `db.places.createIndex({ location: '2dsphere' })` enables $near, $geoWithin queries. These are Mongo's own thing, no SQL equivalent without extensions.

Common mistakes

Forgetting unique constraint on email (duplicate users). Indexing every field (writes slow, RAM bloats). Compound index in wrong direction for sort (only ASC + DESC reverse work). Skipping explain(), you don't know if your index is used until you check.

Sign in and purchase access to unlock this lesson.

Sign in to purchase
←Aggregation Pipeline
Back to MongoDB
Schema Design (Embed vs Reference)→