Compound Indexes क्या हैं
एक compound index कई fields cover करता है, और fields का order decide करता है यह किन queries serve कर सकता है।
In this page:
Syntax
db.collection_name.createIndex({ field1: 1, field2: -1 })
Compound Indexes
db.collection.createIndex({ a: 1, b: -1 }) पहले a फिर b से sort करता है। Index a पर queries support करता है, और a और b साथ पर (prefix rule), लेकिन अकेले b पर नहीं। इस guideline follow करें: पहले equality fields, फिर sort fields, फिर range fields (ESR)।
Note:
ESR rule याद रखें: Equality, Sort, Range।
उदाहरण: Compound indexes
test> db.orders.createIndex({ status: 1, createdAt: -1, total: 1 })
status_1_createdAt_-1_total_1
// Uses the index: status equality, then sorted by createdAt, then total range
test> db.orders.find({ status: "paid", total: { $gt: 100 } }).sort({ createdAt: -1 })
// Cannot use it efficiently: skips the leading field status
test> db.orders.find({ total: { $gt: 100 } })
⚠️ Run this in your own terminal or Node.js environment.
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the
view already swaps in the hi_ translation fields (or blanks these
out if untranslated), so this renders correctly for both languages
without a lang_code check here. #}
आम गलतियां
- equality fields से पहले range fields रखना
- यह उम्मीद करना कि b-only queries एक {a, b} index इस्तेमाल करेंगी
- कई overlapping indexes बनाना
चैप्टर सारांश
- कई fields पर एक index
- Prefix rule: leading fields matter करती हैं
- ESR rule: equality, sort, range order इस्तेमाल करें
- Field order important है
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: