Mongo db项目不在组中的字段

时间:2017-12-08 06:42:06

标签: mongodb mongoose collections

我想知道我是否可以在项目领域中存在。 例如,我有以下收藏品,我想要所有学生中足球最高的学生的名字

{ "_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

1 个答案:

答案 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
        }
    }
])

说明:

  • $group - 按分数对学生进行分组。
  • $sort - 按降序对文档进行排序。
  • $limit - 仅获取第一个文档(评分值最高的文档)。
  • $unwind - 将“names”数组拆分为单独的文档。
  • $project - 生成最终结果(具有已定义形状的文档)。
相关问题