【问题标题】:How to select documents with values above the average如何选择值高于平均值的文档
【发布时间】:2015-10-14 22:33:05
【问题描述】:

我有一个学生集合,其中包含具有以下结构的文档:

{
  "student_name": "john",
  "score": 39,
}

我想选择分数高于所有学生平均分的学生。

我尝试过关注,但它只返回一名学生。

db.students.find().sort({"score":-1}).limit(1).pretty()

如果超过一个学生的最高分,我想获得整个学生集。

【问题讨论】:

标签: mongodb mongodb-query aggregation-framework


【解决方案1】:

您需要使用.aggregate() 方法和$avg 累加器运算符。

var average = db.students.aggregate([
    { "$group": { "_id": "null", avg: { "$avg": "$score"} }}
]).toArray()[0]["avg"];

然后使用.find()方法

db.students.find({ "score": { "$gt": average } })

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-10-30
    • 1970-01-01
    • 2016-09-04
    • 1970-01-01
    • 2020-01-23
    • 1970-01-01
    • 2017-02-18
    • 1970-01-01
    相关资源
    最近更新 更多