【问题标题】:Mongo db project a field not in the groupMongodb项目一个不在组中的字段
【发布时间】:2018-05-22 09:14:26
【问题描述】:

我想知道我是否可以项目组中不存在的字段。 例如,我有以下集合,我想要所有学生中足球最高的学生的名字

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

【问题讨论】:

    标签: mongodb mongoose collections


    【解决方案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 - 将“名称”数组拆分为单独的文档。
    • $project - 生成最终结果(具有定义形状的文档)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-01-10
      • 1970-01-01
      • 2019-08-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多