ให้เราสร้างคอลเลกชันที่มีเอกสารก่อน -
> db.demo121.insertOne( ... { ... "Id" : 101, ... "Details" : [ ... { ... "SubjectId" : "1", ... "SubjectName" : "MongoDB", ... "Score" : 76 ... }, ... { ... "SubjectId" : "2", ... "SubjectName" : "MySQL", ... "Score" : 76 ... }, ... { ... "SubjectId" : "3", ... "SubjectName" : "Java", ... "Score" : 76 ... } ... ] ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5e2f1c60140daf4c2a3544b3") }
แสดงเอกสารทั้งหมดจากคอลเล็กชันโดยใช้วิธี find() -
> db.demo121.find();
สิ่งนี้จะสร้างผลลัพธ์ต่อไปนี้ -
{ "_id" : ObjectId("5e2f1c60140daf4c2a3544b3"), "Id" : 101, "Details" : [ { "SubjectId" : "1", "SubjectName" : "MongoDB", "Score" : 76 }, { "SubjectId" : "2", "SubjectName" : "MySQL", "Score" : 76 }, { "SubjectId" : "3", "SubjectName" : "Java", "Score" : 76 } ] }
ต่อไปนี้เป็นแบบสอบถามเพื่อใช้ฟังก์ชันรวม -
> db.demo121.aggregate([ ... { "$match": { "Id": 101 } }, ... { "$unwind": "$Details" }, ... { ... "$group": { ... "_id": "$Details.SubjectId", ... "count": { "$sum": 1 }, ... "Details": { ... "$push": { ... "SubjectName": "$Details.SubjectName" ... } ... } ... } ... }, ... { ... "$group": { ... "_id": null, ... "List": { ... "$push": { ... "SubId": "$_id", ... "Details": "$Details" ... } ... } ... } ... } ... ], function (err, out) { ... res.json(out); ... });
สิ่งนี้จะสร้างผลลัพธ์ต่อไปนี้ -
{ "_id" : null, "List" : [ { "SubId" : "3", "Details" : [ { "SubjectName" : "Java" } ] }, { "SubId" : "2", "Details" : [ { "SubjectName" : "MySQL" } ] }, { "SubId" : "1", "Details" : [ { "SubjectName" : "MongoDB" } ] } ] }