mongodb-aggregate聚合查询分组后如何获得多字段

2020-10-15 15:50发布

有如下记录:
{“_id”:ObjectId(“7bc”),”user”:”阮七”,”age”:19,”class”:”初三”,”math_score”:10,”eng_score”:76}
{“_id”:ObjectId(“7bd”),”user”:”张怪”,”age”:23,”class”:”大三”,”math_score”:19,”eng_score”:12}
{“_id”:ObjectId(“7be”),”user”:”李九”,”age”:20,”class”:”大三”,”math_score”:98,”eng_score”:23}
{“_id”:ObjectId(“7bf”),”user”:”张丰”,”age”:27,”class”:”博硕”,”math_score”:12,”eng_score”:80}
{“_id”:ObjectId(“7c0″),”user”:”葫娃”,”age”:48,”class”:”成教”,”math_score”:10,”eng_score”:12}
{“_id”:ObjectId(“7c1″),”user”:”哪吒”,”age”:55,”class”:”成教”,”math_score”:96,”eng_score”:49}

1)希望按照class分组,找出math_score值最大的整条记录(文档),如class为‘大三’的整行:
{“_id”:ObjectId(“7be”),”user”:”李九”,”age”:20,”class”:”大三”,”math_score”:98,”eng_score”:23}

2)希望按照class分组,找出 math_score+eng_score 和最小的整条记录(文档),如class为‘大三’的整行:
{“_id”:ObjectId(“7bd”),”user”:”张怪”,”age”:23,”class”:”大三”,”math_score”:19,”eng_score”:12}

刚接触mongodb,没能自己搞出来,敬请指点!

db.stu.aggregate([
{
$group:{
_id:"$class",
maxMathScore:{$max:"$math_score"}
//// 最大分数有了,但最大分数的学生姓名怎么搞?
}
}
])

谢谢!

1条回答
来,给爷笑一个
2楼-- · 2020-10-15 16:28

db.stu.aggregate([
    {$sort:{math_score:-1}}, # 首先进行排序,后续的分组以有序记录为基础
    {$group:{
        user: { "$first":"$$CURRENT.user" },# $$CURRENT即$first所指的组内第1行
        _id:"$class",
        age: { "$first":"$$CURRENT.age" },
        maxMathScore:{$max:"$math_score"} # 取组内最大的分数
    }}
])

查看更多
登录 后发表回答