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

การกรองคิวรีบนอาร์เรย์ของเอกสารฝังใน MongoDB

ใช้ aggregate() กรองเอกสารฝัง 3 ระดับ

เมื่อมีโครงสร้างข้อมูลซ้อนหลายชั้น ใช้ $unwind แยกชั้นทีละขั้นตอน แล้วค่อย $match และ $project

สร้างข้อมูลตัวอย่าง 3 ระดับ

> db.demo736.insertOne({
    "_id": "101",
    "details1": [ { "details2": [ { "details3": { "Name": "John" } } ] } ]
});
> db.demo736.insertOne({
    "_id": "102",
    "details1": [ { "details2": [ { "details3": { "Name": "Robert" } } ] } ]
});

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

> db.demo736.find();

ผลลัพธ์:

{ "_id" : "101", "details1" : [ { "details2" : [ { "details3" : { "Name" : "John" } } ] } ] }
{ "_id" : "102", "details1" : [ { "details2" : [ { "details3" : { "Name" : "Robert" } } ] } ] }

คิวรีกรองเอกสารที่มีชื่อ "Robert" ในระดับลึกสุด

> db.demo736.aggregate([
    { "$unwind": "$details1" },
    { "$unwind": "$details1.details2" },
    { "$match": { "details1.details2.details3.Name": "Robert" } },
    { $project: { _id: 0, Name: "$details1.details2.details3" } }
])

ผลลัพธ์

{ "Name" : { "Name" : "Robert" } }