ใช้ aggregate() ใน MongoDB พร้อม $group และ $push เพื่อรวมหลายเอกสารที่มีค่า id เดียวกัน เป็นเอกสารเดียวที่มีอาร์เรย์รายละเอียด
สร้างคอลเลกชันพร้อมเอกสาร:
> db.demo248.insertOne({"id":101,"Name":"Chris","Age":21,"CountryName":"US"});
{ "acknowledged" : true, "insertedId" : ObjectId("5e46b6651627c0c63e7dba6d") }
> db.demo248.insertOne({"id":101,"Name":"Bob","Age":22,"CountryName":"UK"});
{ "acknowledged" : true, "insertedId" : ObjectId("5e46b6741627c0c63e7dba6e") }
> db.demo248.insertOne({"id":102,"Name":"Mike","Age":20,"CountryName":"AUS"});
{ "acknowledged" : true, "insertedId" : ObjectId("5e46b6811627c0c63e7dba6f") }
แสดงเอกสารทั้งหมด:
> db.demo248.find();
ผลลัพธ์ - มี 3 เอกสาร แยกตาม _id แม้ id จะซ้ำกัน (101):
คำสั่ง Aggregation ใช้ $group โดย _id = "$id" และ $push สร้างอาร์เรย์ details:
> db.demo248.aggregate([ ... { ... $group : { ... _id : "$id", ... details : { ... $push : { ... id:"$id", ... Name:"$Name", ... Age:"$Age", ... CountryName:"$CountryName" ... } ... } ... } ... } ...])ผลลัพธ์ - รวมเป็น 2 เอกสาร: id 101 มี 2 รายการใน details, id 102 มี 1 รายการ: