嵌套对象查询 mongoDB

Nest Object query mongoDB

我有一个文件集,其中包含以下格式的电影信息:

   {
      "_id": "100063",
      "_rev": "1-90d4068b3946fe809a9c9022f1e1c354",
      "title": "The Love She Sought",
      "year": 1990,
      "rating": null,
      "runtime": "100 min",
      "genre": [
        "Drama"
      ],
      "director": "Joseph Sargent",
      "writer": [
        "Jon Hassler (novel)",
        "Ron Cowen (teleplay)",
        "Daniel Lipman (teleplay)"
      ],
      "cast": [
        "Angela Lansbury",
        "Denholm Elliott",
        "Cynthia Nixon",
        "Gary Hershberger"
      ],
      "poster": "http://ia.media-imdb.com/images/M/MV5BMjEwODQzODc2Nl5BMl5BanBnXkFtZTgwMDY2ODk1MDE@._V1_SX300.jpg",
      "imdb": {
        "rating": 7.9,
        "votes": 747,
        "id": "tt0100063"
      }
    }

问题是:找出 2007 年上映的电影的平均票数

我尝试了 $unwind 但它没有用, 这是我的代码

db.movies.aggregate([

 { $unwind: "$imdb"},

 {$group : { _id: "$year", 
              avgVote : { $avg : "$imdb.votes" }
 }},
 { $match: {"year": 2007}
])

您不需要 $unwind 阶段,因为 $unwind 用于将数组字段解构为多个文档,而 imdb 字段 不是array,但是是一个 object.

并将$match阶段移动到第一阶段,尽快过滤文档以获得更好的查询性能。

db.collection.aggregate([
  {
    $match: {
      "year": 2007
    }
  },
  {
    $group: {
      _id: "$year",
      avgVote: {
        $avg: "$imdb.votes"
      }
    }
  }
])

Sample Mongo Playground