2016-03-08 43 views
1

請建議從mongodb的記錄中找到第二高的價值的例子?從mongodb的記錄中找出第二高的價值

{ 
       $group: { 
        _id: "$studentName", 
        //course: { $ifNull: [ "$course", "MBA" ] }, 
        exam: {$push: "$exam"}, 
        course: {$push: "$course"}, 
        school: {$push: "$school"}, 
        Percentage: {$avg: "$marks"}, 
        maximum_mark: {$max: "$marks"}, 
        minimum_mark: {$min: "$marks"} 
       } 


    } 
+2

可能重複[如何在聚合MongoDB中找到次高值](http://stackoverflow.com/questions/35861084/how-to-find-second-highest-value-in-aggregate-mongodb) – profesor79

+1

最高基於哪個鍵值? – Saleem

+0

[MongoDB:如何從集合中找到第n個最高工資]的可能副本(http://stackoverflow.com/questions/32822058/mongodb-how-to-find-nth-highest-salary-from-collection) – Vishwas

回答

1

根據你的問題描述。 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 } 
0

你可以用$sort通過任何你需要$skip的第一個結果排序,然後$limit它1的結果。

問題解決。