请建议从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"}
}
}
答案 0 :(得分:2)
根据您的问题描述。可以通过mark
和$max
运算符检索$min
的最大值和最小值。要查找mark
的第二个高值,可以先通过$sort
,然后$push
到all_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个结果。
问题解决了。