2016-03-08 32 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的结果。

问题解决。