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.

3
  • Use $filter Commented Jan 29, 2017 at 21:49
  • How can you do this? Commented Jan 29, 2017 at 22:13
  • You need to use the $unwind aggregate function Commented Jan 29, 2017 at 22:33

1 Answer 1

3

You need to use aggregation framework:

db.movies.aggregate([
{
    $unwind : "$movies"
},
{
    $match : {
        "movies.director" : "George Lucas"
    }
},
{
    $project : {
        _id : 0,
        movies : 1
    }
}
])
Sign up to request clarification or add additional context in comments.

3 Comments

Throws an error when I run that.
@JohnNoob: I missed the $ in unwind stage. Edited the answer. Should be fine now.
Yep works now.. Just have to go read up on what the hell you did now

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.