Skip to content
BackendDatabaseExpressJsMongoDBNodeJs

5. MongoDB Indexing – Query Speed बढ़ने करने का आसान तरीका

April 29, 2026 11 min read

नमस्ते दोस्तों! 🙏
स्वागत है The Easy Master पर!

क्या तुमने कभी सोचा है – Database query slow kyun ho jati hai? 1 लाख documents में search करने में 10-15 seconds lagte hain? Kyu? Index nahi hai!

Indexing वही है जो किताब के पीछे लगा इंडेक्स – बिना इंडेक्स के तुम पूरी किताब पढ़ते हो, इंडेक्स से सीधा पन्ना खोलते हो.

MongoDB indexing Hindi में समझना बहुत जरूरी है क्योंकि:

  • COLLSCAN vs IXSCAN – 1M docs में 1M scans vs सिर्फ 20 scans
  • Query 100x faster हो सकती है
  • Interview में पक्का indexing questions puche jayenge
  • Production app mein indexing must है

Aaj kya seekhoge?

TopicKya Seekhega?
Index Kya Hai?Linear vs Binary search
COLLSCAN vs IXSCANQuery plan samjho
Single Field Indexएक field पर index
Compound IndexMultiple fields
Multikey IndexArray fields
Text IndexFull-text search
TTL IndexAuto-delete expired data
explain()Query analysis
Best PracticesProduction tips

Kya tumhe pata hai?
Index के बिना 1M documents में 999,999 को खोजने में 999,999 iterations लगते हैं, index से सिर्फ 20!

तो चलिए शुरू करते हैं – MongoDB indexing Hindi सीखने का सफर! 🚀

Table of Contents

1. Index Kya Hai? – Introduction

Index ek special data structure hai (B-tree) जो किसी field के values को sorted order में store करता है.

Real-world Analogy:

Code
📚 किताब का Index:
बिना Index → पूरी किताब पढ़नी पड़ेगी (COLLSCAN)
Index के साथ → "Index" देखो, सीधा पन्ना खोलो (IXSCAN)

Index कैसे काम करता है:

Code
// बिना Index (COLLSCAN)
db.users.find({ age: 25 })
// MongoDB 1M documents में से हर document check करेगा!

// Index के साथ (IXSCAN)
db.users.createIndex({ age: 1 })
db.users.find({ age: 25 })
// MongoDB सीधा age=25 वाले documents ढूंढेगा!

2. Linear Search vs Binary Search – समझो क्यों Fast Hai

Index क्यूं fast है? क्योंकि यह Binary Search use करता है.

Linear Search (बिना Index):

Code
// हर item एक-एक करके check करना
function linearSearch(arr, target) {
    for (let i = 0; i < arr.length; i++) {
        if (arr[i] === target) return i;
    }
    return -1;
}
// 1,000,000 items में 1,000,000 iterations!

Binary Search (Index के साथ):

Code
// हर step में आधे items को हटा देना
function binarySearch(arr, target) {
    let left = 0, right = arr.length - 1;
    while (left <= right) {
        const mid = Math.floor((left + right) / 2);
        if (arr[mid] === target) return mid;
        if (arr[mid] < target) left = mid + 1;
        else right = mid - 1;
    }
    return -1;
}
// 1,000,000 items में सिर्फ 20 iterations!

Performance Comparison:

Code
Dataset Size: 1,000,000 items

Target     Linear Iterations    Binary Iterations
10                    10                   20
500,000          500,000                    1
999,999          999,999                   19
-1             1,000,000                   19

Index का magic यही है – Binary Search!

3. COLLSCAN vs IXSCAN – Query Plan

MongoDB में दो तरह के scans होते हैं:

COLLSCAN (Collection Scan – बिना Index):

Code
// पूरा collection scan होता है
db.movies.find({ "awards.wins": 5 }).explain("executionStats")

Output:

Code
{
  "executionStats": {
    "executionStages": { "stage": "COLLSCAN" },  // ❌ पूरा scan!
    "totalDocsExamined": 21349,   // 21,349 documents scan!
    "nReturned": 24,              // सिर्फ 24 returned
    "totalKeysExamined": 0,       // कोई index use नहीं
    "executionTimeMillis": 21
  }
}

IXSCAN (Index Scan – Index के साथ):

Code
// Index create करो
db.movies.createIndex({ "awards.wins": 1 })

// अब query करो
db.movies.find({ "awards.wins": { "$gt": 30 } }).explain("executionStats")

Output:

Code
{
  "executionStats": {
    "executionStages": {
      "stage": "FETCH",
      "inputStage": { "stage": "IXSCAN" }  // ✅ Index use किया!
    },
    "totalKeysExamined": 331,    // सिर्फ 331 keys
    "totalDocsExamined": 331,    // सिर्फ 331 docs
    "nReturned": 326,
    "executionTimeMillis": 1      // 21ms से 1ms! 🚀
  }
}

Difference: 21,349 docs scanned → 331 docs scanned! 64x faster!

4. Single Field Index – एक Field पर Index

सबसे basic index – एक field पर.

Create Index:

Code
// Ascending order (1)
db.users.createIndex({ email: 1 })

// Descending order (-1)
db.users.createIndex({ createdAt: -1 })

// Unique index (duplicate values not allowed)
db.users.createIndex({ email: 1 }, { unique: true })

Query Examples:

Code
// ये queries index use करेंगी
db.users.find({ email: "vivek@example.com" })
db.users.find({ email: { $in: ["a@b.com", "c@d.com"] } })
db.users.find({ email: { $regex: "^rahul" } }) // prefix regex

// Sort query
db.users.find().sort({ createdAt: -1 }) // descending index use karega

Check if Index is Used:

Code
db.users.find({ email: "vivek@example.com" }).explain("executionStats")
// देखो: "stage": "IXSCAN" होना चाहिए

5. Compound Index – Multiple Fields

Compound index multiple fields पर बनता है.

Create Compound Index:

Code
// status और createdAt पर index
db.orders.createIndex({ status: 1, createdAt: -1 })

ESR Rule (Equality, Sort, Range):

Code
// Query: status = "active", sort by createdAt, price > 100
db.orders.find({
  status: "active",
  price: { $gt: 100 }
}).sort({ createdAt: -1 })

// Index order according to ESR Rule:
// E (Equality) → status: 1
// S (Sort) → createdAt: -1
// R (Range) → price: 1
db.orders.createIndex({ status: 1, createdAt: -1, price: 1 })

Most Left Prefix Rule:

Code
// Index: { a: 1, b: 1, c: 1 }

// ✅ ये queries index use करेंगी:
db.collection.find({ a: 5 })           // Prefix {a}
db.collection.find({ a: 5, b: 10 })    // Prefix {a, b}
db.collection.find({ a: 5, b: 10, c: 15 }) // Full index

// ❌ ये queries index use नहीं करेंगी:
db.collection.find({ b: 10 })           // No {a} prefix
db.collection.find({ b: 10, c: 15 })    // No {a} prefix
db.collection.find({ c: 15 })           // No {a} prefix

6. Multikey Index – Array Fields

जब field array हो, तो Multikey index automatically ban जाता है.

Create Multikey Index:

Code
// Document: { name: "Server A", tags: ["web", "production", "nginx"] }

// Array field पर index
db.servers.createIndex({ tags: 1 })

// Query use karegi index
db.servers.find({ tags: "production" })
db.servers.find({ tags: { $in: ["web", "api"] } })

Important Limitations:

Code
// ✅ Allowed: एक array field
db.collection.createIndex({ tags: 1, category: 1 })  // category non-array

// ❌ Error: दो array fields एक साथ
db.collection.createIndex({ tags: 1, categories: 1 })  // दोनों arrays!

Text index full-text search के लिए.

Create Text Index:

Code
// एक field पर
db.articles.createIndex({ content: "text" })

// Multiple fields पर
db.articles.createIndex({ title: "text", content: "text" })

// With weights (importance)
db.articles.createIndex(
  { title: "text", content: "text" },
  { weights: { title: 10, content: 1 } }  // title 10x important
)

Text Search Queries:

Code
// Basic search
db.articles.find({ $text: { $search: "mongodb indexing" } })

// Phrase search (exact match)
db.articles.find({ $text: { $search: "\"query optimization\"" } })

// Exclude words
db.articles.find({ $text: { $search: "mongodb -sql" } })

// With relevance score
db.articles.find(
  { $text: { $search: "mongodb performance" } },
  { score: { $meta: "textScore" } }
).sort({ score: { $meta: "textScore" } })

Important Limitations:

Code
// ❌ Collection में सिर्फ ONE text index allowed!
// ❌ $regex text index use नहीं करता
// ❌ Hindi/Chinese support limited (use Atlas Search instead)

8. TTL Index – Auto Delete Expired Data

TTL (Time-To-Live) Index documents को automatically delete करता है.

Create TTL Index:

Code
// 30 days के बाद delete
db.sessions.createIndex(
  { createdAt: 1 },
  { expireAfterSeconds: 2592000 }  // 30 days = 30*24*60*60
)

// Specific expiry date field
db.events.createIndex(
  { expireAt: 1 },
  { expireAfterSeconds: 0 }  // expireAt time पर delete
)

// Document example
db.events.insertOne({
  event: "promotion",
  expireAt: ISODate("2026-12-31")
})

Use Cases:

Use CaseTTL Index
SessionsLogin sessions expire करना
LogsOld logs auto delete
OTP CodesTemporary codes expire
CacheCache entries auto cleanup

9. Unique Index – Duplicate Values Rokna

Unique index duplicate values prevent करता है.

Create Unique Index:

Code
// Email unique
db.users.createIndex({ email: 1 }, { unique: true })

// Compound unique (email + phone combination unique)
db.users.createIndex(
  { email: 1, phone: 1 },
  { unique: true }
)

// Partial unique (only for documents with email)
db.users.createIndex(
  { email: 1 },
  {
    unique: true,
    partialFilterExpression: { email: { $exists: true } }
  }
)

10. explain() – Query Analyze Karna

explain() सबसे important tool है performance analysis के लिए.

explain() Modes:

Code
// 1. queryPlanner (default) – सिर्फ plan दिखाता है
db.collection.find({ age: 25 }).explain()

// 2. executionStats – actual statistics दिखाता है (recommended!)
db.collection.find({ age: 25 }).explain("executionStats")

// 3. allPlansExecution – सभी candidate plans दिखाता है
db.collection.find({ age: 25 }).explain("allPlansExecution")

Reading explain() Output:

Code
{
  "queryPlanner": {
    "winningPlan": {
      "stage": "FETCH",           // Document fetch
      "inputStage": {
        "stage": "IXSCAN",        // ✅ Index use! (IXSCAN good)
        "indexName": "age_1"
      }
    }
  },
  "executionStats": {
    "nReturned": 50,              // Documents returned
    "totalKeysExamined": 50,      // Index keys examined
    "totalDocsExamined": 50,      // Documents examined
    "executionTimeMillis": 2,     // Execution time
    "executionStages": {
      "stage": "FETCH",
      "docsExamined": 50,
      "inputStage": {
        "stage": "IXSCAN",
        "keysExamined": 50
      }
    }
  }
}

Key Metrics to Check:

MetricGoodBadMeaning
stageIXSCANCOLLSCANIndex use vs full scan
totalDocsExamined≈ nReturned>> nReturnedExtra work
totalKeysExamined≈ nReturned>> nReturnedIndex inefficient
executionTimeMillis< 10ms> 100msSlow query

11. Covered Query – Sabse Fast

Covered Query – जब सारे required fields index में ही हों, document fetch नहीं करना पड़ता.

Covered Query Example:

Code
// Index: { status: 1, price: 1 }

// ❌ Not covered – _id default return होता है
db.products.find(
  { status: "active" },
  { status: 1, price: 1 }
)
// _id भी return होगा, जो index में नहीं है

// ✅ Covered query – सिर्फ index fields
db.products.find(
  { status: "active" },
  { status: 1, price: 1, _id: 0 }  // _id exclude करो!
)

// Check in explain()
db.products.find(
  { status: "active" },
  { status: 1, price: 1, _id: 0 }
).explain("executionStats")

// totalDocsExamined: 0 होना चाहिए! (no document fetch)[citation:4][citation:8]

Covered Query Benefits:

  • ⚡ Fastest possible – सिर्फ index पढ़ना
  • 💾 No disk I/O – index usually memory में
  • 📊 totalDocsExamined: 0

12. Index Best Practices

✅ DO’s:

Code
// 1. Create index on frequently queried fields
db.orders.createIndex({ userId: 1, status: 1 })

// 2. Use ESR Rule for compound indexes[citation:4][citation:8]
// Equality → Sort → Range
db.orders.createIndex({ status: 1, createdAt: -1, price: 1 })

// 3. Use partial indexes for filtered data[citation:4]
db.products.createIndex(
  { name: 1 },
  { partialFilterExpression: { active: true } }
)

// 4. Use covered queries when possible[citation:4][citation:8]
db.users.find(
  { email: "test@test.com" },
  { email: 1, _id: 0 }
)

// 5. Monitor with explain()
db.collection.find(query).explain("executionStats")

❌ DON’Ts:

Code
// 1. Don't over-index (every index slows writes)
// ❌ 10+ indexes on one collection

// 2. Don't index low-cardinality fields
// ❌ db.users.createIndex({ gender: 1 }) // only "M" or "F"

// 3. Don't use $regex without ^ prefix
// ❌ db.users.find({ name: /vivek/ }) // no index use

// 4. Don't forget _id exclusion in covered queries
// ❌ db.users.find({}, { email: 1 }) // _id returned

// 5. Don't create unnecessary compound indexes
// If you have { a: 1, b: 1 }, you don't need { a: 1 } separately[citation:8]

13. Common Mistakes + Solutions

Mistake 1: COLLSCAN instead of IXSCAN

Code
// ❌ No index, full collection scan
db.orders.find({ status: "pending" })  // COLLSCAN

// ✅ Create index
db.orders.createIndex({ status: 1 })   // Now IXSCAN[citation:1]

Mistake 2: Wrong field order in compound index

Code
// Query: status + price range
db.orders.find({ status: "active", price: { $gt: 100 } })

// ❌ Range field pehle (index not efficient)
db.orders.createIndex({ price: 1, status: 1 })

// ✅ Equality pehle (ESR Rule)[citation:4]
db.orders.createIndex({ status: 1, price: 1 })

Mistake 3: $regex without ^ prefix

Code
// ❌ No index use
db.users.find({ name: /vivek/ }) // scans everything!

// ✅ With ^ prefix, index use
db.users.find({ name: /^vivek/ }) // uses index on name

// ✅ Better: Use text index for full-text search[citation:9]
db.articles.createIndex({ content: "text" })
db.articles.find({ $text: { $search: "mongodb" } })

Mistake 4: Covered query mein _id bhoolna

Code
// ❌ Not covered (_id returned)
db.users.find({ email: "test@test.com" }, { email: 1 })

// ✅ Covered (_id excluded)
db.users.find({ email: "test@test.com" }, { email: 1, _id: 0 })

14. Quick Cheat Sheet

Index Creation Commands:

Index TypeCommand
Single Fielddb.col.createIndex({ field: 1 })
Compounddb.col.createIndex({ a: 1, b: -1 })
Uniquedb.col.createIndex({ email: 1 }, { unique: true })
Textdb.col.createIndex({ content: "text" })
TTLdb.col.createIndex({ createdAt: 1 }, { expireAfterSeconds: 3600 })
Partialdb.col.createIndex({ field: 1 }, { partialFilterExpression: { active: true } })

Index Management:

Code
// View all indexes
db.collection.getIndexes()

// Drop index
db.collection.dropIndex("index_name")
db.collection.dropIndex({ field: 1 })

// Drop all indexes (except _id)
db.collection.dropIndexes()

// Hide index (test before delete)[citation:4]
db.collection.hideIndex("index_name")

explain() Quick Reference:

Code
// What to check:
// 1. stage = "IXSCAN" → ✅ Good
// 2. stage = "COLLSCAN" → ❌ Add index
// 3. totalDocsExamined ≈ nReturned → ✅ Efficient
// 4. totalDocsExamined >> nReturned → ❌ Inefficient
// 5. totalDocsExamined = 0 → 🏆 Covered query![citation:4]

15. FAQ

Q1: MongoDB indexing Hindi में सबसे important kya hai?
explain("executionStats") – इससे पता चलता है query index use कर रही है या full scan.

Q2: COLLSCAN vs IXSCAN – kya antar hai?
COLLSCAN = पूरा collection scan (slow), IXSCAN = index scan (fast).

Q3: Index query ko fast kyu banata hai?
Index B-tree structure use करता है – binary search से O(log n) time, linear search से बहुत fast.

Q4: Compound index mein field order kyu important hai?
ESR Rule (Equality → Sort → Range) follow करो. Wrong order से index inefficient हो जाता है.

Q5: Text index vs $regex – kya use karein?
Full-text search के लिए text index use करो[$regex से performance बहुत खराब होती है.

Q6: TTL index kya karta hai?
Documents को auto delete करता है specified time के बाद – sessions, logs, OTP के लिए perfect.

Q7: Covered query kya hai?
Query result सिर्फ index से आता है, document fetch नहीं होता – fastest possible.

Q8: Unique index kyu use karein?
Duplicate values prevent करने के लिए – email, phone number fields पर.

Q9: Index writes ko slow kyu karta hai?
Har write operation index को भी update करता है – insert/update/delete slow हो सकते हैं.

Q10: Partial index kya hai?
Sirf specific documents पर index – size छोटा, performance better.

16. Conclusion

बहुत बढ़िया दोस्तों! आज हमने MongoDB indexing Hindi को पूरी detail में समझा.

Quick Recap:

Index TypeUse Case
Single Fieldएक field पर query
CompoundMultiple fields + ESR Rule
MultikeyArray fields
TextFull-text search
TTLAuto-delete expired data
UniqueDuplicate prevention

Mera personal experience:

जब पहली बार index use किया, 50,000 documents वाली query 3 seconds से 30ms पर आ गई. Indexing के बिना production app impossible है. पहले query pattern समझो, फिर index बनाओ.

Tum bhi ye steps follow karo:

  1. ✅ Slow query ढूंढो (explain() use करके)
  2. ✅ Frequently queried fields पर index बनाओ
  3. ✅ Compound index में ESR Rule follow करो
  4. ✅ Covered queries के लिए projection use करो
  5. ✅ Unused indexes को हटाओ

अब तुम्हारी बारी है!

नीचे comment में बताओ:

  1. तुमने कभी index use kiya है?
  2. कौन सी query slow थी?
  3. अगला topic क्या चाहिए? (MongoDB Aggregation Pipeline? Performance Tuning? Atlas Search?)

The Easy Master पर बने रहो। Happy Indexing! 🚀🍃

Resources

Additional Resources

TheEasyMaster

Author at The Easy Master.

Related posts

Leave a Reply

Your email address will not be published. Required fields are marked *