สำหรับสิ่งนี้ ให้ใช้ $group ร่วมกับ $max ใน MongoDB ให้เราสร้างคอลเลกชันที่มีเอกสาร -
> db.demo510.insertOne( ... { ... details:[ ... { ... Name:"Chris", ... Score:56 ... }, ... { ... Name:"David", ... Score:45 ... } ... ] ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5e8845fa987b6e0e9d18f582") } > db.demo510.insertOne( ... { ... details:[ ... { ... Name:"Chris", ... Score:56 ... }, ... { ... Name:"David", ... Score:47 ... } ... ] ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5e8845fb987b6e0e9d18f583") } > db.demo510.insertOne( ... { ... details:[ ... { ... Name:"Chris", ... Score:45 ... }, ... { ... Name:"David", ... Score:91 ... } ... ] ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5e8845fb987b6e0e9d18f584") }
แสดงเอกสารทั้งหมดจากคอลเล็กชันโดยใช้วิธี find() -
> db.demo510.find();
สิ่งนี้จะสร้างผลลัพธ์ต่อไปนี้ -
{ "_id" : ObjectId("5e8845fa987b6e0e9d18f582"), "details" : [ { "Name" : "Chris", "Score" : 56 }, { "Name" : "David", "Score" : 45 } ] } { "_id" : ObjectId("5e8845fb987b6e0e9d18f583"), "details" : [ { "Name" : "Chris", "Score" : 56 }, { "Name" : "David", "Score" : 47 } ] } { "_id" : ObjectId("5e8845fb987b6e0e9d18f584"), "details" : [ { "Name" : "Chris", "Score" : 45 }, { "Name" : "David", "Score" : 91 } ] }
ต่อไปนี้เป็นแบบสอบถามเพื่อจับคู่และจัดกลุ่มองค์ประกอบอาร์เรย์ที่มีค่าสูงสุดในการรวม -
> db.demo510.aggregate([ ... { "$project": { ... "details": { ... "$arrayElemAt": [ ... { "$filter": { ... "input": "$details", ... "as": "res", ... "cond": { ... "$eq": [ ... "$$res.Score", ... { "$max": { ... "$map": { ... "input": "$details", ... "as": "out", ... "in": "$$out.Score" ... } ... }} ... ] ... } ... }}, ... 0 ... ] ... } ... }}, ... { "$group": { ... "_id": "$details.Name", ... "Name": { "$first": "$details.Name" }, ... "count": { "$sum": 1 } ... }} ... ])
สิ่งนี้จะสร้างผลลัพธ์ต่อไปนี้ -
{ "_id" : "David", "Name" : "David", "count" : 1 } { "_id" : "Chris", "Name" : "Chris", "count" : 2 }