ใช้ Dot Notation ใน find() สำหรับ Query ฟิลด์ซ้อน
สามารถ query ฟิลด์ภายในออบเจ็กต์ซ้อนในอาร์เรย์ได้โดยตรงด้วย dot notation เช่น "parent.array.field"
ตัวอย่างข้อมูล
> db.demo455.insertOne({ "Information": { "Student": [{ "Name": "Chris", "Age": 22 }] } });
> db.demo455.insertOne({ "Information": { "Student": [{ "Name": "David", "Age": 21 }] } });
> db.demo455.insertOne({ "Information": { "Student": [{ "Name": "Bob", "Age": 24 }] } });
> db.demo455.insertOne({ "Information": { "Student": [{ "Name": "Robert", "Age": 21 }] } });
Query หานักเรียนอายุ 21 ปี
> db.demo455.find({ "Information.Student.Age": 21 });
ผลลัพธ์
{ "_id": ObjectId(...), "Information": { "Student": [{ "Name": "David", "Age": 21 }] } }
{ "_id": ObjectId(...), "Information": { "Student": [{ "Name": "Robert", "Age": 21 }] } }
คำอธิบาย
Information.Student.Age- MongoDB จะค้นหาในทุกอิลิเมนต์ของอาร์เรย์ Student- ถ้าอิลิเมนต์ไหนมี Age = 21 เอกสารทั้งฉบับจะถูกคืน
- ทำงานได้กับอาร์เรย์ที่มีหลายอิลิเมนต์ (Multi-key index)
ตัวอย่างเพิ่มเติม
// หานักเรียนอายุ 21-23
db.demo455.find({ "Information.Student.Age": { $gte: 21, $lte: 23 } });
// หานักเรียนชื่อขึ้นต้นด้วย C
db.demo455.find({ "Information.Student.Name": { $regex: "^C" } });
// ใช้ $elemMatch เมื่อต้อง match หลายฟิลด์ในอิลิเมนต์เดียวกัน
db.demo455.find({ "Information.Student": { $elemMatch: { Name: "David", Age: 21 } } });
Index สำหรับ Query นี้
db.demo455.createIndex({ "Information.Student.Age": 1 });