MongoDB รองรับการเข้าถึงฟิลด์ใน Nested Object (Object ซ้อน Object) โดยใช้ Dot Notation ทั้งใน query และ projection
รูปแบบ Dot Notation
"parentField.childField.grandChildField"
ตัวอย่าง: Nested Object 4 ระดับ
1. สร้างข้อมูลตัวอย่าง
> db.nestedObjectDemo.insertOne({
"Student" : {
"StudentDetails" : {
"StudentPersonalDetails" : {
"StudentName" : [ "John" ],
"StudentCountryName" : [ "US" ],
"StudentCoreSubject" : [ "C", "Java" ],
"StudentProject" : [ "Online Book Store", "Pig Dice Game" ]
}
}
}
});
2. แสดงข้อมูลทั้งหมด
> db.nestedObjectDemo.find().pretty();
{
"_id" : ObjectId("..."),
"Student" : {
"StudentDetails" : {
"StudentPersonalDetails" : {
"StudentName" : [ "John" ],
"StudentCountryName" : [ "US" ],
"StudentCoreSubject" : [ "C", "Java" ],
"StudentProject" : [ "Online Book Store", "Pig Dice Game" ]
}
}
}
}
3. Query ด้วย Dot Notation (หา StudentName = "John")
> db.nestedObjectDemo.find({
"Student.StudentDetails.StudentPersonalDetails.StudentName": "John"
}).pretty();
การใช้งาน Dot Notation ในกรณีต่างๆ
| กรณี | ตัวอย่าง |
|---|---|
| Query filter | { "a.b.c": "value" } |
| Projection (include) | { "a.b.c": 1 } |
| Projection (exclude) | { "a.b.c": 0 } |
| Update (set) | { $set: { "a.b.c": "newValue" } } |
| Sort | { "a.b.c": 1 } |