ดึงข้อมูลจาก Nested Array ด้วย Dot Notation ใน MongoDB
บทความนี้สาธิตการใช้ Dot Notation (การชี้ฟิลด์ด้วยจุด) เพื่อ Query และ Project ข้อมูลจากอาร์เรย์ที่ซ้อนกันหลายชั้น (Deeply Nested Arrays) ใน MongoDB
ขั้นตอนที่ 1: สร้าง Collection และเพิ่มข้อมูลตัวอย่าง
สร้าง collection ชื่อ extractParticularElementDemo โครงสร้างซ้อน 4 ชั้น: StudentInformation -> StudentPersonalInformation -> StudentFamilyDetails -> FatherName
> db.extractParticularElementDemo.insertOne({
"_id": 101,
"StudentName": "John",
"StudentInformation": [{
"Age": 21,
"StudentPersonalInformation": [
{
"StudentNickName": "Mike",
"StudentFamilyDetails": [{ "FatherName": "Carol" }]
},
{
"StudentAnotherName": "David",
"StudentFamilyDetails": [{ "FatherName": "Robert" }]
}
]
}]
});
{ "acknowledged": true, "insertedId": 101 }
ขั้นตอนที่ 2: แสดงข้อมูลทั้งหมด
> db.extractParticularElementDemo.find().pretty();
ขั้นตอนที่ 3: Query และ Project ด้วย Dot Notation
Query: หาเอกสารที่ FatherName = "Carol" ในลึก
Projection: ดึงเฉพาะ Path เดียวกัน และซ่อน _id
> db.extractParticularElementDemo.find(
{'StudentInformation.StudentPersonalInformation.StudentFamilyDetails.FatherName': 'Carol'},
{'StudentInformation.StudentPersonalInformation.StudentFamilyDetails.FatherName': 1, "_id": 0}
).pretty();
ผลลัพธ์ที่ได้
{ "StudentInformation": [{
"StudentPersonalInformation": [
{ "StudentFamilyDetails": [{ "FatherName": "Carol" }] },
{ "StudentFamilyDetails": [{ "FatherName": "Robert" }] }
]
}] }
สรุป: Dot Notation ใน MongoDB ช่วยให้สามารถ Query และ Project ฟิลด์ลึกใน Nested Arrays ได้โดยตรง แต่จะคืนค่าทั้ง Path รวมถึง Sibling elements ในระดับเดียวกัน (ไม่ใช่แค่ Element ที่ Match เท่านั้น)