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

การคิวรีบนอาร์เรย์ของอ็อบเจกต์เพื่อดึงเอกสารฝังเฉพาะใน MongoDB

ใช้ $elemMatch ใน find()

$elemMatch ใช้จับคู่เงื่อนไขหลายอย่างภายในอิลิเมนต์เดียวของอาร์เรย์

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

> db.demo763.insertOne({
    _id:1,
    CountryName:"US",
    "studentInformation": [
        { StudentName:"Chris" },
        { StudentName:"David", StudentAge:22 }
    ]
});

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

> db.demo763.find();

ผลลัพธ์:

{ "_id" : 1, "CountryName" : "US", "studentInformation" : [ { "StudentName" : "Chris" }, { "StudentName" : "David", "StudentAge" : 22 } ] }

คิวรีดึงเฉพาะอิลิเมนต์ในอาร์เรย์ที่มีฟิลด์ StudentAge

> db.demo763.find({},
{
    studentInformation: {
        $elemMatch: {
            StudentAge: { $exists: true }
        }
    }
})

ผลลัพธ์: แสดงเฉพาะอิลิเมนต์ที่มี StudentAge

{ "_id" : 1, "studentInformation" : [ { "StudentName" : "David", "StudentAge" : 22 } ] }