ใช้ dot notation กับ distinct()
เมธอด distinct() รองรับ dot notation เพื่อเข้าถึงฟิลด์ภายใน sub-document หรืออาร์เรย์ของ sub-document
ไวยากรณ์
db.yourCollectionName.distinct("yourOuterFieldName.yourInnerFieldName");
ตัวอย่าง
สร้างคอลเลกชัน getDistinctListOfSubDocumentFieldDemo ที่มีฟิลด์ StudentPersonalDetails เป็นอาร์เรย์ของออบเจกต์:
> db.getDistinctListOfSubDocumentFieldDemo.insertOne({
"StudentId": 101,
"StudentPersonalDetails": [
{"StudentName": "John", "StudentAge": 24},
{"StudentName": "Carol", "StudentAge": 21}
]
});
> db.getDistinctListOfSubDocumentFieldDemo.insertOne({
"StudentId": 102,
"StudentPersonalDetails": [
{"StudentName": "Carol", "StudentAge": 26},
{"StudentName": "Bob", "StudentAge": 21}
]
});
> db.getDistinctListOfSubDocumentFieldDemo.insertOne({
"StudentId": 103,
"StudentPersonalDetails": [
{"StudentName": "Bob", "StudentAge": 25},
{"StudentName": "David", "StudentAge": 24}
]
});
ดึงค่า StudentName ที่ไม่ซ้ำกัน
> db.getDistinctListOfSubDocumentFieldDemo.distinct("StudentPersonalDetails.StudentName");
ผลลัพธ์:
[ "Carol", "John", "Bob", "David" ]
MongoDB จะดูทุกอิลิเมนต์ในอาร์เรย์ StudentPersonalDetails และรวบรวมค่า StudentName ที่ไม่ซ้ำกัน