Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> MongoDB

วิธีเข้าถึง Nested Object ใน MongoDB ด้วย Dot Notation

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 ในกรณีต่างๆ

ข้อควรระวัง

  • Dot notation ใช้ได้กับ Object ซ้อน Object (ไม่ใช่ Array of Objects)
  • ถ้ามี Array ต้องใช้ positional operator $ หรือ $elemMatch
  • ชื่อฟิลด์ที่มีจุด (.) ต้อง Escape หรือใช้ bracket notation ใน driver

สรุป

Dot Notation เป็นวิธีมาตรฐานในการเข้าถึง Nested Object ใน MongoDB ใช้ได้ใน query, projection, update, sort ทุกอย่าง เขียนเป็น string คั่นด้วยจุด

กรณีตัวอย่าง
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 }