从mongodb的记录中找到第二高的值

时间:2016-03-08 12:31:33

标签: mongodb mongodb-query

请建议从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 个答案:

答案 0 :(得分:2)

根据您的问题描述。可以通过mark$max运算符检索$min的最大值和最小值。要查找mark的第二个高值,可以先通过$sort,然后$pushall_marks运算符中的数组$group,然后获得第二个高值价值通过$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 }

答案 1 :(得分:0)

您可以使用$sort按照您需要$skip第一个结果进行排序,然后$limit将其排序为1个结果。

问题解决了。