【发布时间】:2020-06-16 11:12:06
【问题描述】:
我有以下 json 数据:
{ "_id" : { "Soid" : "50b59cd75bed76f46522c36a" }, "student_id" : 4, "class_id" : 5, "scores" : [ { "type" : "exam", "score" : 5.466727688497352 }, { "type" : "quiz", "score" : 48.70365097712529 }, { "type" : "homework", "score" : 84.00121183981668 }, { "type" : "homework", "score" : 67.53163246780703 }, { "type" : "homework", "score" : 66.19091789853015 } ] },
{ "_id" : { "Soid" : "50b59cd75bed76f46522c354" }, "student_id" : 0, "class_id" : 7, "scores" : [ { "type" : "exam", "score" : 18.20492211025179 }, { "type" : "quiz", "score" : 60.4769945611789 }, { "type" : "homework", "score" : 75.62999921143397 }, { "type" : "homework", "score" : 72.41228797373115 }, { "type" : "homework", "score" : 74.06744381708968 } ] },
{ "_id" : { "Soid" : "50b59cd75bed76f46522c358" }, "student_id" : 0, "class_id" : 10, "scores" : [ { "type" : "exam", "score" : 30.93065784731665 }, { "type" : "quiz", "score" : 55.98003281528393 }, { "type" : "homework", "score" : 55.6752702814148 }, { "type" : "homework", "score" : 63.15391302252755 } ] },
我想找出在“考试”、“测验”和“家庭作业”等每种考试类型中获得的最高分。
我知道我可以使用 mongos aggregate() 并且我知道如何获得这样的最大值:
db.grades.aggregate(
[
{
$group:
{
_id: "Soid",
{$scores: maxQuantity: { $max: "$score" }}
}
}
]
)
但是我如何到达嵌套部分并确定那里的最大值?我尝试使用 unwind 函数,但我不知道确切的语法。
【问题讨论】:
-
您可以先找到最高分,然后将该分数与每个项目进行比较。或者您可以创建一个数组并在其上使用
$reduce。但是您当前的代码似乎无效,没有$scores运算符,$group中的对象不是有效的 javascript 对象。
标签: database mongodb aggregate