首页 > 解决方案 > mongodb:查询平均大于数字的文档

问题描述

如何找到平均分大于 5 的文档。集合如下所示:
集合餐厅:

{"grades": [{"grade": "A", "score": 2}, {"grade": "A", "score": 6}], "name": "Morris Park Bake Shop", "restaurant_id": "30075445"}

{"grades": [{"grade": "A", "score": 8}, {"grade": "B", "score": 23}], "name": "Wendy'S", "restaurant_id": "30112340"}

{"grades": [{"grade": "A", "score": 2}, {"grade": "A", "score": 11}], "name": "Dj Reynolds Pub And Restaurant", "restaurant_id": "30191841"}

我试过了

db.restaurants.find({average_socre: {$gt: 5}}, {average_socre:{$avg: "$grades.score"}})

但它不起作用。

标签: mongodbmongodb-query

解决方案


使用此查询:

db.collection.find({
  $expr: {
    $gt: [
      {
        "$avg": "$grades.score"
      },
      5
    ]
  }
},
{
  average_score: {
    $avg: "$grades.score"
  }
})

居住


推荐阅读