← Back to MongoDB Course | Chapter 8: Indexes | Lesson 2 of 7

createIndex() का उपयोग

createIndex एक या ज़्यादा fields पर, ascending या descending, एक index बनाता है।

In this page:

  1. createIndex()
Syntax
javascript
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()

bash
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. #}
आम गलतियां
  1. duplicate indexes बनाना
  2. ज़रूरत पड़ने पर unique भूल जाना
  3. 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:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.