การเข้าถึงค่าภายใน nested JSON object/array ใน MongoDB ใช้ Dot Notation ใน find() projection หรือ query filter ได้โดยตรง ไม่ต้อง aggregate
สร้างคอลเลกชันและข้อมูลตัวอย่าง (โครงสร้างซ้อน 3 ระดับ)
> db.demo235.insertOne({
"id": 101,
"details": [
{ "Name": "Chris Brown", "Age": 21 },
{ "Name": "David Miller", "Age": 24 }
],
"otherdetails": [
{ "Score": 56, "Subject": "MongoDB" },
{ "Score": 78, "Subject": "MySQL" }
]
});
{ "acknowledged" : true, "insertedId" : ObjectId("5e418d22f4cebbeaebec514b") }
แสดงข้อมูล
> db.demo235.find().pretty();
ผลลัพธ์: 1 เอกสาร มี details array (2 objects) และ otherdetails array (2 objects)
Query ดึงเฉพาะ Subject จาก otherdetails Array
> db.demo235.find({}, {"otherdetails.Subject": 1, _id: 0});
คำอธิบาย:
- Filter:
{}(ทุกเอกสาร) - Projection:
{"otherdetails.Subject": 1, _id: 0}- include เฉพาะ Subject ใน otherdetails array, exclude _id - MongoDB จะคืนค่า array of objects ที่มีเฉพาะ field Subject
ผลลัพธ์
{ "otherdetails" : [ { "Subject" : "MongoDB" }, { "Subject" : "MySQL" } ] }
Dot Notation Patterns
| Pattern | คำอธิบาย | ตัวอย่าง |
|---|---|---|
object.field | Nested object | {"details.Name": 1} |
array.field | ทุก element ใน array | {"details.Name": 1} → [{Name}, {Name}] |
array.index.field | Element index เฉพาะ | {"details.0.Name": 1} → element แรก |
array.nested.field | Deep nesting | {"details.0.address.city": 1} |