Mongodb 我可以用“吗?”$“第一”;“a”中两个字段上的运算符$“集团”;mongo db中的操作?
以数据集为例Mongodb 我可以用“吗?”$“第一”;“a”中两个字段上的运算符$“集团”;mongo db中的操作?,mongodb,Mongodb,以数据集为例 { "_id" : { "$oid" : "aaa" }, "student_id" : 0, "type" : "exam", "score" : 54.6535436362647 } { "_id" : { "$oid" : "bbb" }, "student_id" : 0, "type" : "quiz", "score" : 31.95004496742112 } { "_id" : { "$oid" : "ccc" }, "student_id" :
{ "_id" : { "$oid" : "aaa" }, "student_id" : 0, "type" : "exam", "score" : 54.6535436362647 }
{ "_id" : { "$oid" : "bbb" }, "student_id" : 0, "type" : "quiz", "score" : 31.95004496742112 }
{ "_id" : { "$oid" : "ccc" }, "student_id" : 0, "type" : "homework", "score" : 14.8504576811645 }
{ "_id" : { "$oid" : "ddd" }, "student_id" : 0, "type" : "homework", "score" : 63.98402553675503 }
{ "_id" : { "$oid" : "eee" }, "student_id" : 1, "type" : "exam", "score" : 74.20010837299897 }
{ "_id" : { "$oid" : "fff" }, "student_id" : 1, "type" : "quiz", "score" : 96.76851542258362 }
{ "_id" : { "$oid" : "ggg" }, "student_id" : 1, "type" : "homework", "score" : 21.33260810416115 }
{ "_id" : { "$oid" : "hhh" }, "student_id" : 1, "type" : "homework", "score" : 44.31667452616328 }
比如说,对于每个学生,我需要找到最低分数和相应的文档id(_id)
这是我的管道
pipeline = [
{"$sort":{"student_id":1,"score":1 } },
{"$group": {"_id":"$student_id","mscore":{"$first":"$score"},"docid":{"$first":"$_id"} } },
{"$sort":{"_id":1}},
{"$project":{"docid":1,"_id":0}}
]
虽然这很好,但我不确定这是因为我有正确的查询,还是因为数据的存储方式
这是我的战略
按学生id排序,分数根据学生id分组,并首先进行评分,它将给出学生id、最小分数 现在,我还需要这个minu分数的doc_id(_id),所以我也在该字段上使用first。对吗
比如说,在排序之后,我需要完整的第一个文档,所以我应该首先在每个字段上应用,还是有其他方法可以做到这一点 要在排序后获取整个第一个文档,请对引用根文档(即当前在操作员管道阶段处理的顶级文档)的系统变量应用运算符。您的管道将如下所示:
var pipeline = [
{
"$sort": { "score": 1 }
},
{
"$group": {
"_id": "$student_id",
"data": { "$first": "$$ROOT" }
}
},
{
"$project": {
"_id": "$data._id",
"student_id": "$data.student_id",
"type": "$data.type",
"lowest_score": "$data.score"
}
}
]
在多个字段上使用first是否也像我在问题中所做的那样正确?这意味着它会给我我想要的吗?@伙计,是的,它会给我同样的结果。