Find all movies that are considered Action or Adventure and return only the title of the movie in NoSQL

Viewed 24

I am not to sure of what to do. I tried combining $and & $or syntax but my code keeps coming up wrong. I have tried projection. and have a feeling I may need to run the queries separate.

This is the last code I have tried running in VS code in the mongodb playground:

db.movies.find(
    { $and : [
        { $or : [  { genre: { $eq: "Action" } }, { genre: $eq:"Adventure"},
        { $or : [ { title: "Wonder Woman" }, { title: 1 },
        { $or : [ { title: "Cloud Atlas" }, { title: 1 },
        { $or : [ { title: "Pan's Labyrinth"}, { title: 1 },
        { $or : [ { title: "Gone With the Wind"}, { title: 1 },
        { $or : [ { title: "Spaceballs"}, { title: 1 },
        { $or : [ { title: "Silence of the Lambs"}, { title: 1 },
        { $or : [ { title: "American History X"}, { title: 1 },
        { $or : [ { title: "Psycho"}, { title: 1 },
        { $or : [ { title: "The Pianist"}, { title: 1 },
        { $or : [ { title: "Gladiator"},{ title: 1 } } ] }
    ]}
)

can any one assist with what I may be doing wrong and what I could do?

1 Answers

You are just mixing the project object which is in charge of returning only certain fields and the query object which is in charge of filtering documents.

Here is how it'll look fixed:

db.collection.find({
  $or: [
    {
      genre: "Action"
    },
    {
      genre: "Adventure"
    }
  ]
},
{
  _id: 0,
  title: 1
})

You can also clean it up a little and use the $in operator instead:

db.collection.find({
  genre: {
    $in: [
      "Action",
      "Adventure"
    ]
  }
},
{
  _id: 0,
  title: 1
})

Mongo Playground

Related