MongoDB में $elemMatch क्वेरी के लिए इंडेक्स उपयोग विश्लेषण
explain() विधि का उपयोग करके आप यह जांच सकते हैं कि आपकी क्वेरी इंडेक्स का उपयोग कर रही है या नहीं। $elemMatch के साथ इंडेक्स उपयोग विशिष्ट शर्तों पर निर्भर करता है।
इंडेक्स बनाना और डेटा डालना
> db.workingOfIndexesDemo.createIndex(
{"Information.StudentDetails.StudentName":1},
{ sparse: true, background: true }
);
{ "createdCollectionAutomatically" : true, "numIndexesBefore" : 1, "numIndexesAfter" : 2, "ok" : 1 }
> db.workingOfIndexesDemo.insertOne({"Information":{"StudentDetails":{"StudentName":"Chris"}}});
> db.workingOfIndexesDemo.insertOne({"Information":{"StudentDetails":{"StudentName":"David"}}});
> db.workingOfIndexesDemo.insertOne({"Information":{"StudentDetails":{"StudentName":"Mike"}}});
दस्तावेज़ देखना
> db.workingOfIndexesDemo.find();
आउटपुट:
नोट: डेटा संरचना ऐरे नहीं है
इस उदाहरण में
StudentDetailsएक **ऑब्जेक्ट** है, ऐरे नहीं। इसलिए$elemMatchयहां अनावश्यक है और इंडेक्स उपयोग को प्रभावित कर सकता है।$elemMatch के साथ explain()
> db.workingOfIndexesDemo.find({ "Information.StudentDetails": { $elemMatch: { "StudentName" : "David" } } }).explain();मुख्य आउटपुट भाग (winningPlan):
विश्लेषण
- IXSCAN: इंडेक्स स्कैन उपयोग किया गया - इंडेक्स काम कर रहा है!
- filter: $elemMatch फिल्टर FETCH स्टेज पर लागू होता है
- isMultiKey: false: क्योंकि StudentDetails ऐरे नहीं है
- indexBounds: इंडेक्स "David" तक सीमित है
$elemMatch के साथ इंडेक्स उपयोग के नियम
- ऐरे फ़ील्ड पर इंडेक्स: यदि फ़ील्ड ऐरे है, तो इंडेक्स मल्टीकी होता है (
isMultiKey: true) - सिंगल फ़ील्ट इंडेक्स: $elemMatch की शर्तें इंडेक्स प्रीफिक्स से मेल खानी चाहिए
- कंपाउंड इंडेक्स: $elemMatch एक ही ऐरे के अंदर एकाधिक फ़ील्ड्स के लिए कंपाउंड इंडेक्स का उपयोग कर सकता है
सही इंडेक्स बनाना (ऐरे के लिए)
निष्कर्ष
उदाहरण में इंडेक्स **काम कर रहा है** (IXSCAN दिखाता है)। $elemMatch इंडेक्स उपयोग को नहीं रोकता जब क्वेरी पैटर्न इंडेक्स परिभाषा से मेल खाता है।