聚合管道后获取id值
Get id value after aggregating pipeline
考虑名为 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 的方法是否正确。
使用 $first
和 $sort
升序而不是 $min
来拉入具有最低分数的整个文档 ($$ROOT
) 并映射必填字段。
db.col.aggregate([
{"$match":{"type":"homework"}},
{"$sort":{"score":1}},
{"$group":{
"_id":"$student_id",
"doc":{"$first":{"score":"$$ROOT.score","_id":"$$ROOT._id"}}
}}
])
考虑名为 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 的方法是否正确。
使用 $first
和 $sort
升序而不是 $min
来拉入具有最低分数的整个文档 ($$ROOT
) 并映射必填字段。
db.col.aggregate([
{"$match":{"type":"homework"}},
{"$sort":{"score":1}},
{"$group":{
"_id":"$student_id",
"doc":{"$first":{"score":"$$ROOT.score","_id":"$$ROOT._id"}}
}}
])