MSK Institute LogoMSK.Institute
HomeCourses
Book Free Demo➔Sign In
Free Demo➔
MSK Institute LogoMSK.Institute

Leading computer training academy in Shikohabad for software engineering, Python, web development, and digital literacy.

ISO 9001:2015 Certified Center
Follow & Connect
4.9

Programs & Admissions

  • All CoursesCatalog
  • Learning PathsRoadmaps
  • Student ProjectsShowcase
  • Live Classes & ScheduleLive
  • Upcoming Batches
  • Campuses & LocationsHub
  • Verify Certificates
  • Book Free Demo Class

Resources & Tools

  • Free Online Mock TestsAll Tests
  • NIELIT CCC Mock TestFree
  • Course & Career FinderQuiz
  • Study Material Hub
  • All MSK ToolsHub
  • Keyboard ShortcutsNew
  • TypeQuest Speed LabTyping
  • MSK Code PlaygroundCode
  • Interactive Tutorials
  • Quick Cheatsheets

Institute & Contact

  • About MSK Institute
  • Careers & InternshipsHiring
  • Publications & Blogs
  • Gali No. 3, Near Gyan Jyoti Public School,
    Adarsh Nagar, Shikohabad, Uttar Pradesh 283135
  • +91 83930 42166
  • mskshikohabad@gmail.com
  • Hours:Mon – Sat: 8:00 AM – 7:00 PM | Sun: 10:00 AM – 2:00 PM
  • 4.9 ★(38 Google Reviews)
© 2026 MSK Institute. All rights reserved.•Privacy Policy•Terms of Service•Disclaimer•Contact Us

Shikohabad's Leading Computer & Coding Academy

Home
Courses
Live
Material
Database Indexing Strategies (Single, Compound, TTL) & Query Optimization0%
Study Materials
MongoDB & MongooseProgress 0%
1.1Document Databases vs Relational SQL: CAP Theorem & When to Use NoSQL1.2JSON vs BSON Data Types & MongoDB Internal Storage Engine (WiredTiger)1.3MongoDB Atlas Cloud Setup, Network Whitelisting & Compass GUI
4.1One-to-Few (Embedded) vs One-to-Many (Referenced) Data Modeling4.2Query Population with .populate() & Multi-Level Population4.3Aggregation Pipeline Architecture: $match, $group, $project & $sort4.4Multi-Table Joins with $lookup & Array Flattening with $unwind4.5Database Indexing Strategies (Single, Compound, TTL) & Query Optimization
HomeTutorialsMongoDB & MongooseDatabase Indexing Strategies (Single, Compound, TTL) & Query Optimization

Database Indexing Strategies (Single, Compound, TTL) & Query Optimization

Beginner12 min read•Updated: 2026-11-18•By Er. Sumit Kumar (MSK Institute)
Study MaterialsCheatsheet

Without indexes, MongoDB must inspect every single document in a collection to satisfy a query—an expensive operation known as a Collection Scan (COLLSCAN). Proper Indexing Strategies turn sluggish multi-second queries into sub-millisecond Index Scans (IXSCAN).


1. Types of MongoDB Indexes

  1. 1
    Single Field Index: Index on a single attribute (db.users.createIndex({ email: 1 })).
  2. 2
    Compound Index: Index on multiple fields (db.courses.createIndex({ category: 1, price: -1 })).
  3. 3
    Unique Index: Guarantees no two documents share the same value ({ unique: true }).
  4. 4
    TTL (Time-To-Live) Index: Automatically deletes documents after a designated lifespan!
  5. 5
    Text Index: Powers full-text keyword searches across text fields.

2. The ESR Rule for Compound Indexes

When designing compound indexes for complex queries containing Equality, Sorting, and Range conditions, follow the ESR (Equality, Sort, Range) Rule:

  1. 1
    E - Equality: Fields queried with exact matches (status: 'ACTIVE') go first.
  2. 2
    S - Sort: Fields used for ordering (sort: { createdAt: -1 }) go second.
  3. 3
    R - Range: Fields queried with range operators (price: { $gte: 100 }) go last.
1// Query:
2db.orders.find({ status: 'COMPLETED', totalAmount: { $gte: 500 } }).sort({ orderDate: -1 });
3 
4// Optimal Index following ESR:
5db.orders.createIndex({
6 status: 1, // 1. Equality
7 orderDate: -1, // 2. Sort
8 totalAmount: 1 // 3. Range
9});

3. TTL (Time-To-Live) Indexes for Auto-Expiring Data

Use TTL indexes to automatically purge temporary verification OTPs, login tokens, or shopping carts:

1const tokenSchema = new Schema({
2 userId: Schema.Types.ObjectId,
3 token: String,
4 createdAt: {
5 type: Date,
6 default: Date.now,
7 expires: 3600 // Automatically deleted by MongoDB background thread after 1 hour (3600s)!
8 }
9});

4. Query Profiling with explain("executionStats")

To verify if your query is using an index, run .explain("executionStats"):

1const stats = await Course.find({ slug: 'full-stack-mern-mastery' })
2 .explain('executionStats');
3 
4console.log('Stage:', stats.executionStats.executionStages.stage);
5console.log('Docs Examined:', stats.executionStats.totalDocsExamined);
6console.log('Keys Examined:', stats.executionStats.totalKeysExamined);
  • COLLSCAN: Full collection scan (Bad! Means missing index).
  • IXSCAN: Index scan (Good! Direct B-Tree traversal).

Interactive Quiz• Knowledge Check

Multiple Choice Questions

Question 1
What does the stage COLLSCAN in a MongoDB query explain plan signify?
Question 2
What is the ESR Rule for designing optimal compound indexes in MongoDB?
Question 3
What does a TTL (Time-To-Live) index do in MongoDB?
Question 4
Why should you NOT indiscriminately create dozens of indexes on every single field of a collection?
Question 5
What does the stage IXSCAN followed by a FETCH indicate in an explain plan?

Related Lessons

Previous LessonNext Lesson
Multi-Table Joins with $lookup & Array Flattening with $unwindNone

Practice Quiz

Test your understanding of this lesson with 5 questions. Each question has one correct answer.

Mentor-Led Practical Training

Master MongoDB & Mongoose with Hands-On Projects

Practice in live mentor-led sessions with real projects, mock tests, and verifiable certification at MSK Institute.

View Full CourseBook Free Demo
Previous
PreviousPrevNext