सब-डॉक्यूमेंट फील्ड के विशिष्ट (distinct) मान प्राप्त करें
MongoDB में नेस्टेड (सब-डॉक्यूमेंट) फील्ड के विशिष्ट मान पाने के लिए डॉट (.) नोटेशन के साथ distinct() मेथड का उपयोग करें।
सिंटैक्स
db.yourCollectionName.distinct("yourOuterFieldName.yourInnerFieldName");
उदाहरण: StudentPersonalDetails ऐरे में StudentName के विशिष्ट मान
> db.getDistinctListOfSubDocumentFieldDemo.insertOne({
"StudentId": 101,
"StudentPersonalDetails": [
{"StudentName": "John", "StudentAge": 24},
{"StudentName": "Carol", "StudentAge": 21}
]
});
{ "acknowledged" : true, "insertedId" : ObjectId("5c90a9abb74d7cfe6392d7d8") }
> db.getDistinctListOfSubDocumentFieldDemo.insertOne({
"StudentId": 102,
"StudentPersonalDetails": [
{"StudentName": "Carol", "StudentAge": 26},
{"StudentName": "Bob", "StudentAge": 21}
]
});
{ "acknowledged" : true, "insertedId" : ObjectId("5c90a9ceb74d7cfe6392d7d9") }
> db.getDistinctListOfSubDocumentFieldDemo.insertOne({
"StudentId": 103,
"StudentPersonalDetails": [
{"StudentName": "Bob", "StudentAge": 25},
{"StudentName": "David", "StudentAge": 24}
]
});
{ "acknowledged" : true, "insertedId" : ObjectId("5c90a9e6b74d7cfe6392d7da") }
सभी दस्तावेज़:
> db.getDistinctListOfSubDocumentFieldDemo.find().pretty();
विशिष्ट नाम प्राप्त करें
> db.getDistinctListOfSubDocumentFieldDemo.distinct("StudentPersonalDetails.StudentName");व्याख्या: डॉट नोटेशन
StudentPersonalDetails.StudentNameऐरे के अंदर प्रत्येक ऑब्जेक्ट केStudentNameफील्ड तक पहुंचता है और डुप्लिकेट हटाकर विशिष्ट मान लौटाता है।