createIndex() का उपयोग
createIndex एक या ज़्यादा fields पर, ascending या descending, एक index बनाता है।
In this page:
Syntax
db.collection_name.createIndex({ field: 1 })
db.collection_name.createIndex({ field: 1 }, { unique: true })
createIndex()
db.collection.createIndex({ field: 1 }) एक ascending index बनाता है (descending के लिए -1, जो single fields के लिए rarely matter करता है)।
Options में duplicates रोकने के लिए unique, सिर्फ कुछ documents index करने के लिए sparse और partial, और TTL indexes के लिए expireAfterSeconds शामिल हैं। बड़ी collections पर Index builds resources इस्तेमाल करते हैं, इसलिए इन्हें plan करें।
Note:
एक unique index data integrity भी enforce करता है, जैसे unique emails।
उदाहरण: createIndex()
test> db.users.createIndex({ email: 1 }, { unique: true })
email_1
test> db.users.insertMany([{ email: "[email protected]" }, { email: "[email protected]" }])
MongoBulkWriteError: E11000 duplicate key error collection: shop.users index: email_1 dup key: { email: "[email protected]" }
test> db.sessions.createIndex({ createdAt: 1 }, { expireAfterSeconds: 3600 })
createdAt_1
⚠️ 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. #}
आम गलतियां
- duplicate indexes बनाना
- ज़रूरत पड़ने पर unique भूल जाना
- peak load पर बड़े indexes बनाना
चैप्टर सारांश
- createIndex({ field: 1 }) से index बनता है
- unique duplicates रोकता है
- partial और sparse subsets index करते हैं
- TTL indexes documents expire करते हैं
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: