MongoDB में कंपाउंड इंडेक्स के साथ एकाधिक फील्ड्स को इंडेक्स करना
MongoDB में एकाधिक फील्ड्स पर क्वेरी प्रदर्शन को बेहतर बनाने के लिए कंपाउंड इंडेक्स बनाए जाते हैं। createIndex() (या पुराने संस्करणों में ensureIndex()) का उपयोग करके आप एक ही इंडेक्स में कई फील्ड्स को शामिल कर सकते हैं।
उदाहरण: इंडेक्स बनाना और दस्तावेज़ डालना
> db.demo53.createIndex({"StudentFirstName":1,"StudentAge":1});
{ "createdCollectionAutomatically" : true, "numIndexesBefore" : 1, "numIndexesAfter" : 2, "ok" : 1 }
> db.demo53.createIndex({"StudentFirstName":1,"StudentCountryName":1});
{ "createdCollectionAutomatically" : false, "numIndexesBefore" : 2, "numIndexesAfter" : 3, "ok" : 1 }
> db.demo53.insertOne({"StudentFirstName":"Chris","StudentAge":21,"StudentCountryName":"US"});
{ "acknowledged" : true, "insertedId" : ObjectId("5e271431cfb11e5c34d89911") }
> db.demo53.insertOne({"StudentFirstName":"David","StudentAge":23,"StudentCountryName":"UK"});
{ "acknowledged" : true, "insertedId" : ObjectId("5e27143ccfb11e5c34d89912") }
> db.demo53.insertOne({"StudentFirstName":"Mike","StudentAge":24,"StudentCountryName":"AUS"});
{ "acknowledged" : true, "insertedId" : ObjectId("5e27144bcfb11e5c34d89913") }
सभी दस्तावेज़ देखना
> db.demo53.find();
आउटपुट:
{ "_id" : ObjectId("5e271431cfb11e5c34d89911"), "StudentFirstName" : "Chris", "StudentAge" : 21, "StudentCountryName" : "US" }
{ "_id" : ObjectId("5e27143ccfb11e5c34d89912"), "StudentFirstName" : "David", "StudentAge" : 23, "StudentCountryName" : "UK" }
{ "_id" : ObjectId("5e27144bcfb11e5c34d89913"), "StudentFirstName" : "Mike", "StudentAge" : 24, "StudentCountryName" : "AUS" }
महत्वपूर्ण नोट्स:
- कंपाउंड इंडेक्स क्रम मायने रखता है: इंडेक्स में फील्ड्स का क्रम क्वेरी पैटर्न से मेल खाना चाहिए
- ESR नियम: समानता (Equality) → सॉर्ट (Sort) → रेंज (Range) के क्रम में फील्ड्स रखें
ensureIndex()अब डिप्रिकेटेड है;createIndex()का उपयोग करें- एक ही फील्ड से शुरू होने वाले कई इंडेक्स्स बनाए जा सकते हैं (यहां StudentFirstName)
ये इंडेक्स्स StudentFirstName और StudentAge या StudentCountryName पर क्वेरी को ऑप्टिमाइज़ करेंगे।