MongoDB में कंपाउंड यूनिक इंडेक्स बनाना
कंपाउंड इंडेक्स एकाधिक फ़ील्ड्स पर बनाया जाता है। unique: true के साथ, इंडेक्स कीड फ़ील्ड्स का **संयोजन** यूनिक होना चाहिए, व्यक्तिगत फ़ील्ड्स नहीं।
कंपाउंड यूनिक इंडेक्स बनाना
> db.compoundIndexDemo.createIndex(
{"StudentName":1, "StudentAge":1},
{unique:true}
);
{ "createdCollectionAutomatically" : true, "numIndexesBefore" : 1, "numIndexesAfter" : 2, "ok" : 1 }
दस्तावेज़ डालना
> db.compoundIndexDemo.insertOne({"StudentName":"Chris"});
{ "acknowledged" : true, "insertedId" : ObjectId("5e084c1d25ddae1f53b62207") }
> db.compoundIndexDemo.insertOne({"StudentName":"Chris","StudentAge":23});
{ "acknowledged" : true, "insertedId" : ObjectId("5e084c5625ddae1f53b62209") }
> db.compoundIndexDemo.insertOne({"StudentName":"Chris","StudentAge":22});
{ "acknowledged" : true, "insertedId" : ObjectId("5e084c5b25ddae1f53b6220a") }
डुप्लिकेट संयोजन डालने का प्रयास (त्रुटि)
> db.compoundIndexDemo.insertOne({"StudentName":"Chris","StudentAge":23});
2019-12-29T12:19:02.225+0530 E QUERY [js] WriteError: E11000 duplicate key error collection: web.compoundIndexDemo index: StudentName_1_StudentAge_1 dup key: { : "Chris", : 23.0 }
WriteError({ "index" : 0, "code" : 11000, "errmsg" : "E11000 duplicate key error collection: web.compoundIndexDemo index: StudentName_1_StudentAge_1 dup key: { : \"Chris\", : 23.0 }", ... })
दस्तावेज़ देखना
> db.compoundIndexDemo.find().pretty();
आउटपुट:
मुख्य अवधारणा: कंपाउंड यूनिकनेस
| दस्तावेज़ | StudentName | StudentAge | संयोजन | अनुमत? |
|---|---|---|---|---|
| 1 | Chris | (अनुपस्थित) | ("Chris", null) | हां |
| 2 | Chris | 23 | ("Chris", 23) | हां |
| 3 | Chris | 22 | ("Chris", 22) | हां |
| 4 | Chris | 23 | ("Chris", 23) | नहीं - डुप्लिकेट |
"फिक्स्ड वैल्यू फ़ील्ड" का अर्थ
शीर्षक में "फिक्स्ड वैल्यू फ़ील्ड" का अर्थ है कि एक फ़ील्ड (StudentName) कई दस्तावेज़ों में समान हो सकती है, लेकिन **संयोजन** यूनिक होना चाहिए। यह "आंशिक यूनिकनेस" जैसा व्यवहार करता है।
उपयोग के मामले
- यूज़र + रोल संयोजन यूनिक होना चाहिए
- ऑर्डर + प्रोडक्ट संयोजन यूनिक (डुप्लिकेट ऑर्डर लाइन रोकें)
- ईमेल + टेनेंट संयोजन (मल्टी-टेनेंसी)
स्पार्स कंपाउंड इंडेक्स
यह null/अनुपस्थित फ़ील्ड्स वाले दस्तावेज़ों को इंडेक्स से बाहर रखता है।