Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading