有如下记录:
{“_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"}
//// 最大分数有了,但最大分数的学生姓名怎么搞?
}
}
])
谢谢!
- MongoDB can not create unique sparse index (duplic
- Spring Data MongoDB - lazy access to some fields
- Golang mongodb aggregation
- How to convert from Timestamp to Mongo ObjectID
- MongoDB Indexing: Multiple single-field vs single
- mongodb有没有什么办法禁止读取数据的时候进行缓存
- mongodb-aggregate聚合查询分组后如何获得多字段
- mongodb-aggregate聚合查询分组后如何获得多字段
- mongodb error: how do I make sure that your journa
- How to track MongoDB requests from a console appli
- MongoError: cannot infer query fields to set, path
- Pymongo $in Query Not Working
- django.core.exceptions.ImproperlyConfigured: '
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"} # 取组内最大的分数
}}
])