Nest Object query mongoDB

I have a collection of documents containing information about movies by following format:

   {
      "_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"
      }
    }

the question is: find out the average votes for movies released in the year 2007

I tried the $unwind but it didn’t work,
here is my code

db.movies.aggregate([

 { $unwind: "$imdb"},

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

>Solution :

You don’t need the $unwind stage as $unwind is used to deconstruct the array field to multiple documents, while the imdb field is not an array, but is an object.

And move the $match stage to the first stage to filter the document as soon as possible for better query performance.

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

Sample Mongo Playground

Leave a Reply