0

Consider this:

{
  "movies": [
    {
      "title": "Star Wars",
      "year": 1977,
      "director": "George Lucas"
    },
    {
      "title": "The Empire Strikes Back",
      "year": 1980,
      "director": "Irvin Kershner"
    },
    {
      "title": "Return of the Jedi",
      "year": 1983,
      "director": "Richard Marquand"
    },
    {
      "title": "The Phantom Menace",
      "year": 1999,
      "director": "George Lucas"
    },
    {
      "title": "Attack of the Clones",
      "year": 2002,
      "director": "George Lucas"
    },
    {
      "title": "Revenge of the Sith",
      "year": 2005,
      "director": "George Lucas"
    },
    {
      "title": "The Force Awakens",
      "year": 2015,
      "director": "J.J. Abrams"
    }
  ]
}

I am trying to pull out all the movies directed by Geroge Lucas. This is what I have tried and it returns all items:

db.movies.find( {"movies.director" : "George Lucas"} ).pretty()

and also this which results in an error:

db.movies.find({"$pull" : {"movies.director" : "George Lucas"}}).pretty()

Please let me know how to query the database to retrieve only movies where the director key has "George Lucas" as the value.

JohnSnow
  • 6,911
  • 8
  • 23
  • 44

1 Answers1

3

You need to use aggregation framework:

db.movies.aggregate([
{
    $unwind : "$movies"
},
{
    $match : {
        "movies.director" : "George Lucas"
    }
},
{
    $project : {
        _id : 0,
        movies : 1
    }
}
])
ares
  • 4,283
  • 6
  • 32
  • 63