【问题标题】:MongoDB Select Values above AverageMongoDB 选择高于平均值的值
【发布时间】:2022-01-03 06:46:19
【问题描述】:

我正在寻找价格高于平均价格的产品。

我知道如何取平均值:

db.products.aggregate([{ 
  "$group": {
    "_id": null, 
    "average": { "$avg": "$price" } 
  }
},
{ $project : { _id : 0 } } ])

但是如何在 $gt 子句中使用它呢?

例如,我尝试将结果保存在变量中:

var averageValue = 
db.products.aggregate([{ 
  "$group": {
    "_id": null, 
    "average": { "$avg": "$price" } 
  }
},
{ $project : { _id : 0 } } ])

然后在$gt子句中使用:

db.products.find({ "price": { "$gt": averageValue} })

但是,它似乎没有打印任何东西。

我也想知道这是否可以在单个查询中完成。

【问题讨论】:

    标签: mongodb nosql aggregation-framework


    【解决方案1】:

    如果您使用 MongoDB 5.0 版,您可以使用$setWindowFields 对集合中的所有文档进行平均,并将结果字段添加到每个文档。

    对集合中指定的文档范围(称为窗口)执行操作,并根据所选窗口运算符返回结果。

    db.products.aggregate([
      {
        "$setWindowFields": {
          "output": {
            "average": {
              "$avg": "$price"
            }
          }
        }
      },
      {
        $match: {
          $expr: {
            $gt: [
              "$price",
              "$average"
            ]
          }
        }
      }
    ])
    

    Sample Mongo Playground

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-10-30
      • 1970-01-01
      • 2016-09-04
      • 1970-01-01
      • 2021-07-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多