我想知道我是否可以在项目领域中存在。 例如,我有以下收藏品,我想要所有学生中足球最高的学生的名字
{ "_id" : 1, "Snmae" : Alex, "score" : 97}
{ "_id" : 2, "Snmae" : Sara, "socre" : 97 }
{ "_id" : 3, "Snmae" : Sam, "socre" : 93 }
{ "_id" : 4, "Snmae" : Dan, "socre" : 77 }
db.stuudent.aggregate(
{$project:{_id:0,sname:1,score:1}},
{ $group : { _id : "", High_Score: { $max: "$score" }}}
);
欲望输出是
Sname:Alex,得分:97
Sname:Sara,得分:97
答案 0 :(得分:1)
数据:
{ "_id" : 1.0, "Sname" : "Alex", "score" : 97.0 },
{ "_id" : 2.0, "Sname" : "Sara", "score" : 97.0 },
{ "_id" : 3.0, "Sname" : "Sam", "score" : 93.0 },
{ "_id" : 4.0, "Sname" : "Dan", "score" : 77.0 }
查询:
db.collection.aggregate([
{
$group: {
_id: "$score",
"names": { $push: "$Sname" }
}
},
{ $sort: { "_id": -1 } },
{ $limit: 1},
{ $unwind: "$names" },
{
$project: {
"Sname": "$names",
"score": "$_id",
"_id": 0
}
}
])
说明: