【发布时间】:2023-03-21 10:56:02
【问题描述】:
考虑名为 sample 的集合中的以下数据
{ "_id" : 1, "student_id" : 10, "type" : "homework", "score" : 63 },
{ "_id" : 3, "student_id" : 10, "type" : "homework", "score" : 14 },
{ "_id" : 2, "student_id" : 10, "type" : "quiz", "score" : 31 },
{ "_id" : 4, "student_id" : 10, "type" : "quiz", "score" : 54 },
{ "_id" : 5, "student_id" : 11, "type" : "homework", "score" : 33 },
{ "_id" : 7, "student_id" : 11, "type" : "homework", "score" : 74 },
{ "_id" : 6, "student_id" : 11, "type" : "quiz", "score" : 51 },
{ "_id" : 8, "student_id" : 11, "type" : "quiz", "score" : 24 }
我想获取每个学生在作业类型中获得的最低分数的_id。
我有以下查询
db.sample.aggregate([
{ $match: { type: 'homework' }, },
{
$group: {
_id: {
student_id: '$student_id',
},
mark: {
$min: '$score',
}
}
}
])
它计算最小标记,但我想要对应的_ids。
上面查询的结果是
{ "_id" : { "student_id" : 11 }, "mark" : 33 }
{ "_id" : { "student_id" : 10 }, "mark" : 14 }
获取 id 的方法是否正确。
【问题讨论】:
标签: mongodb mongodb-query aggregation-framework mongo-shell