【问题标题】:MongoDb query aggregateMongoDb 查询聚合
【发布时间】:2016-10-23 15:50:27
【问题描述】:
db.grades.aggregate({'$group':{'_id':'$student_id', 'score':{'$gte':65}}}, {'$sort':{'score':1}}, {'$limit':1})

我无法弄清楚为什么这不起作用。它应该“查找所有大于或等于 65 的考试分数,并将这些分数从低到高排序。”

它给出了一个错误:

错误:命令失败:{ "ok" : 0, "errmsg" : "unknown group operator '$gte'", "code" : 15952 } : 聚合失败

【问题讨论】:

    标签: mongodb aggregation-framework database


    【解决方案1】:

    我觉得db.grades.find、sort、limit 极其简单。我喜欢。如果需要它使用聚合管道来完成更高级的工作,那么只需将聚合视为一组步骤。它不像 SQL(你将所有内容都塞进一个语句中)。

    相反,请使用聚合管道分层构建您的查询。执行以下一次添加一个元素,你就会明白我的意思了。

    db.grades.aggregate(
      {'$match':{'score':{'$gte':65}}},
      {'$group':{'_id':'$student_id', 'scoreMax':{'$max':'$score'}}},
      {'$sort':{'scoreMax':-1}},
      {'$limit':1}
    )
    

    $match 拉取分数 >= 65。仅使用该元素执行您的管道,您将看到所有匹配的分数。

    db.grades.aggregate(
      {'$match':{'score':{'$gte':65}}}
    )
    

    $group 获得每个 student_id 的最高分(我认为,这就是您的教授希望您使用的)

    db.grades.aggregate(
      {'$match':{'score':{'$gte':65}}},
      {'$group':{'_id':'$student_id', 'scoreMax':{'$max':'$score'}}}
    )
    

    $sort 将汇总的学生列表按顺序排列(从最聪明到最愚蠢)

    db.grades.aggregate(
      {'$match':{'score':{'$gte':65}}},
      {'$group':{'_id':'$student_id', 'scoreMax':{'$max':'$score'}}},
      {'$sort':{'scoreMax':-1}}
    )
    

    $limit 只提取最优秀的学生和她的分数。

    db.grades.aggregate(
      {'$match':{'score':{'$gte':65}}},
      {'$group':{'_id':'$student_id', 'scoreMax':{'$max':'$score'}}},
      {'$sort':{'scoreMax':-1}},
      {'$limit':1}
    )
    

    【讨论】:

    • 解释得很好!不过还是谢谢大家! :)
    【解决方案2】:

    您不能使用$gte insde 组。您可以在$group 阶段之前使用$match 聚合管道阶段并在那里按$gte 过滤。 无论如何,我认为您的查询不需要聚合; 这是否解决了您的问题:

    db.grades.find({'score':{'$gte':65}}).sort({'score':1}).limit(1)
    

    ?

    【讨论】:

    • 感谢您的回答!你的方式有效,但我需要它来使用聚合。 :)
    猜你喜欢
    • 2019-06-18
    • 1970-01-01
    • 2021-09-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-03
    • 2021-06-02
    相关资源
    最近更新 更多