有如下记录:
{“_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,没能自己搞出来,敬请指点!
<code class="hljs language-bash">db.stu.aggregate([ { <span class="hljs-variable">$group</span>:{ _id:<span class="hljs-string">"<span class="hljs-variable">$class</span>"</span>, maxMathScore:{<span class="hljs-variable">$max</span>:<span class="hljs-string">"<span class="hljs-variable">$math_score</span>"</span>} //// 最大分数有了,但最大分数的学生姓名怎么搞? } } ])</code>
谢谢!
以下内容供参考:
db.test.insertMany([
{“user”:”阮七”,”age”:19,”class”:”初三”,”math_score”:10,”eng_score”:76},
{“user”:”张怪”,”age”:23,”class”:”大三”,”math_score”:19,”eng_score”:12},
{“user”:”李九”,”age”:20,”class”:”大三”,”math_score”:98,”eng_score”:23},
{“user”:”张丰”,”age”:27,”class”:”博硕”,”math_score”:12,”eng_score”:80},
{“user”:”葫娃”,”age”:48,”class”:”成教”,”math_score”:10,”eng_score”:12},
{“user”:”哪吒”,”age”:55,”class”:”成教”,”math_score”:96,”eng_score”:49}
]);
db.test.aggregate([{
$sort: {
class: 1,
math_score: -1
}
}, {
$group: {
_id: “$class”,
doc: {
$first: “$$ROOT”
}
}
}])
db.test.aggregate([{
$addFields: {
total_score: {
$add: [“$math_score”, “$eng_score”]
}
}
}, {
$sort: {
class: 1,
total_score: -1
}
}, {
$group: {
_id: “$class”,
doc: {
$first: “$$ROOT”
}
}
}])
谢谢!先用分数排序,而后分组