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

วิธีค้นหาอิลิเมนต์เฉพาะในเอกสารฝังของ MongoDB

ใช้ $unwind, $match, $project ใน Aggregate

แยกอาร์เรย์ด้วย $unwind กรองด้วย $match แล้วเลือกฟิลด์ด้วย $project

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

> db.demo744.insertOne({
    studentInformation: [
        { studentName:"Robert", grade:"A" },
        { studentName:"Bob", grade:"C" },
        { studentName:"John", grade:"B" },
        { studentName:"Sam", grade:"A" }
    ]
});

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

> db.demo744.find();

ผลลัพธ์:

{ "_id" : ObjectId("5ead928a57bb72a10bcf0684"), "studentInformation" : [ { "studentName" : "Robert", "grade" : "A" }, { "studentName" : "Bob", "grade" : "C" }, { "studentName" : "John", "grade" : "B" }, { "studentName" : "Sam", "grade" : "A" } ] }

คิวรีค้นหานักเรียนที่ได้เกรด A

> db.demo744.aggregate(
    { $unwind: '$studentInformation' },
    { $match: {'studentInformation.grade':"A"}},
    { $project: {"studentInformation.studentName": 1}}
)

ผลลัพธ์

{ "_id" : ObjectId("5ead928a57bb72a10bcf0684"), "studentInformation" : { "studentName" : "Robert" } }
{ "_id" : ObjectId("5ead928a57bb72a10bcf0684"), "studentInformation" : { "studentName" : "Sam" } }