根據你的問題描述。 mark
的最大值和最小值可以通過$max
和$min
運算符檢索。要查找的mark
的第二高值,可以通過$sort
在$group
操作來完成第一,然後$push
到一個數組all_marks
,然後通過$arrayElemAt
獲得第二高值,
鑑於數據
{ "_id" : ObjectId("56dfea65199803954abcd1c4"), "studentName" : "name1", "exam"
: "e1", "course" : "math", "school" : "s1", "marks" : 96 }
{ "_id" : ObjectId("56dfeb50199803954abcd1c5"), "studentName" : "name1", "exam"
: "e2", "course" : "math", "school" : "s1", "marks" : 99 }
{ "_id" : ObjectId("56dfeb72199803954abcd1c6"), "studentName" : "name1", "exam"
: "e1", "course" : "english", "school" : "s1", "marks" : 90 }
{ "_id" : ObjectId("56dff03b199803954abcd1c7"), "studentName" : "name2", "exam"
: "e1", "course" : "math", "school" : "s1", "marks" : 86 }
{ "_id" : ObjectId("56dff04d199803954abcd1c8"), "studentName" : "name2", "exam"
: "e2", "course" : "math", "school" : "s1", "marks" : 90 }
{ "_id" : ObjectId("56dff317199803954abcd1c9"), "studentName" : "name2", "exam"
: "e2", "course" : "math", "school" : "s1", "marks" : 81 }
採用聚集
.aggregate([
{$sort: {studentName: 1, marks: -1}},
{$group: {_id:"$studentName",
exam: {$push: '$exam'},
course: {$push: 'course'},
school:{$push: '$school'},
Percentage: {$avg: '$marks'},
max_mark: {$max: '$mark'},
min_mark: {$min: '$mark'},
all_marks: {$push: '$marks'}
}},
{$project: {exam: 1,
course: 1,
school: 1,
Percentage: 1,
max_mark: 1,
min_mark: 1,
second_max_mark: {$arrayElemAt: ['$all_marks', 1]}
}}])
輸出
{ "_id" : "name2", "exam" : [ "e2", "e1", "e2" ], "course" : [ "course", "course
", "course" ], "school" : [ "s1", "s1", "s1" ], "Percentage" : 85.66666666666667
, "max_mark" : null, "min_mark" : null, "second_max_mark" : 86 }
{ "_id" : "name1", "exam" : [ "e2", "e1", "e1" ], "course" : [ "course", "course
", "course" ], "school" : [ "s1", "s1", "s1" ], "Percentage" : 95, "max_mark" :
null, "min_mark" : null, "second_max_mark" : 96 }
可能重複[如何在聚合MongoDB中找到次高值](http://stackoverflow.com/questions/35861084/how-to-find-second-highest-value-in-aggregate-mongodb) – profesor79
最高基於哪個鍵值? – Saleem
[MongoDB:如何從集合中找到第n個最高工資]的可能副本(http://stackoverflow.com/questions/32822058/mongodb-how-to-find-nth-highest-salary-from-collection) – Vishwas