ในการรวมอาร์เรย์ที่ซ้อนกันใน MongoDB ให้ใช้ aggregate() ให้เราสร้างคอลเลกชันที่มีเอกสาร -
> db.demo441.insertOne( ... { ... ... "Name" : "David", ... "Age" : 21, ... ... "details" : [ ... { ... "id" : 1, ... "CountryName" : "US", ... "details1" : [ ... { ... "SubjectName" : "MySQL", ... "Score":56 ... }, ... { ... "SubjectName" : "MongoDB", ... "Score":78 ... } ... ] ... } ... ] ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5e78cc05bbc41e36cc3caeb7") }
แสดงเอกสารทั้งหมดจากคอลเล็กชันโดยใช้วิธี find() -
> db.demo441.find();
สิ่งนี้จะสร้างผลลัพธ์ต่อไปนี้ -
{ "_id" : ObjectId("5e78cc05bbc41e36cc3caeb7"), "Name" : "David", "Age" : 21, "details" : [ { "id" : 1, "CountryName" : "US", "details1" : [ { "SubjectName" : "MySQL", "Score" : 56 }, { "SubjectName" : "MongoDB", "Score" : 78 } ] } ] }
ต่อไปนี้เป็นแบบสอบถามเพื่อรวมอาร์เรย์ที่ซ้อนกัน -
> db.demo441.aggregate([{ ... $addFields: { ... ResultOfDetails: { ... $map: { ... input: "$details", ... as: "output", ... in: { ... id: "$$output.id", ... CountryName: "$$output.CountryName", ... details1: { ... $let: { ... vars: { ... last: { ... $arrayElemAt: ["$$output.details1", -1] ... } ... }, ... in: { ... $cond: [{ ... $eq: ["$$last.Score", 78] ... }, ... ["$$last"], ... [] ... ... } ... } ... } ... } ... } ... } ... } ... }]).pretty();
สิ่งนี้จะสร้างผลลัพธ์ต่อไปนี้ -
{ "_id" : ObjectId("5e78cc05bbc41e36cc3caeb7"), "Name" : "David", "Age" : 21, "details" : [ { "id" : 1, "CountryName" : "US", "details1" : [ { "SubjectName" : "MySQL", "Score" : 56 }, { "SubjectName" : "MongoDB", "Score" : 78 } ] } ], "ResultOfDetails" : [ { "id" : 1, "CountryName" : "US", "details1" : [ { "SubjectName" : "MongoDB", "Score" : 78 } ] } ] }