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

วิธีค้นหาข้อความใน Double Nested Array ของ MongoDB ด้วย Dot Notation

ใช้ Dot Notation เพื่อ Query เข้าไปใน Double Nested Array (อาร์เรย์ซ้อนอาร์เรย์) ได้โดยตรง

โครงสร้างข้อมูลตัวอย่าง

StudentDetails: [
    {
        ProjectName: "Online Banking",
        ProjectDetails: [           // Level 2 Array
            { TechnologyUsed: "Java" },
            { TechnologyUsed: "MySQL in Backend" }
        ]
    }
]

รูปแบบคำสั่ง

db.collection.find({ "outerArray.innerArray.field": "searchValue" })

ตัวอย่างเต็มรูปแบบ

1. สร้างข้อมูล Double Nested Array

> db.doubleNestedArrayDemo.insertOne({
    "StudentId": "1000", "StudentName": "Larry",
    "StudentDetails": [{
        "ProjectName": "Online Banking",
        "ProjectDetails": [
            { "TechnologyUsed": "Java" },
            { "TechnologyUsed": "MySQL in Backend" }
        ]
    }]
});

> db.doubleNestedArrayDemo.insertOne({
    "StudentId": "1001", "StudentName": "Robert",
    "StudentDetails": [{
        "ProjectName": "Student Web Tracker",
        "ProjectDetails": [
            { "TechnologyUsed": "Django Framework" },
            { "TechnologyUsed": "MongoDB in Backend" }
        ]
    }]
});

2. แสดงข้อมูลทั้งหมด

> db.doubleNestedArrayDemo.find().pretty();

3. ค้นหา "Java" ใน Double Nested Array

> db.doubleNestedArrayDemo.find({ 
    "StudentDetails.ProjectDetails.TechnologyUsed": "Java" 
}).pretty();

4. ผลลัพธ์: เจอเฉพาะ Larry (ที่มี Java)

{ 
    "_id" : ObjectId("..."), 
    "StudentId" : "1000", 
    "StudentName" : "Larry", 
    "StudentDetails" : [ 
        { 
            "ProjectName" : "Online Banking", 
            "ProjectDetails" : [ 
                { "TechnologyUsed" : "Java" },
                { "TechnologyUsed" : "MySQL in Backend" }
            ]
        }
    ]
}

คำอธิบาย Dot Notation Path

StudentDetails          // Array Level 1
    .ProjectDetails     // Field ใน Object ของ Level 1 ที่เป็น Array Level 2
    .TechnologyUsed     // Field ใน Object ของ Level 2

MongoDB จะ "Unwind" อัตโนมัติใน Query phase เพื่อ match ทุกระดับ

ข้อจำกัด

  • Query นี้คืน เอกสารทั้งฉบับ (ไม่ใช่แค่ sub-document ที่ match)
  • ถ้าต้องการคืนเฉพาะ sub-document ที่ match ต้องใช้ Aggregation ($unwind, $match, $project)
  • Dot notation ทำงานได้ลึกไม่จำกัดระดับ (ตราบใดที่เป็น Object ซ้อน Object/Array)

สรุป

ใช้ Dot Notation "array1.array2.field" ใน find() เพื่อค้นหาใน Double Nested Array ได้โดยตรง สะดวกและเร็วสำหรับการ filter เอกสาร