Arrays: One Value Means Contains

Every movie has an array of genres. Querying an array field is simple. Give it a single value:

db.movies.find(
  { genres: "drama" },
  { _id: 0, title: 1, genres: 1 }
)

Output:

[
  { title: 'Interstellar', genres: [ 'sci-fi', 'drama' ] },
  { title: 'Parasite', genres: [ 'thriller', 'drama' ] },
  { title: 'Whiplash', genres: [ 'drama', 'music' ] },
  { title: 'Okja', genres: [ 'drama' ] },
  { title: 'First Man', genres: [ 'drama', 'history' ] }
]

The filter { genres: "drama" } compares one value with an array. MongoDB reads it as "the array contains this value". This works for any list of tags, such as the tags on a post or the roles of a user.

If you give the filter an array instead, the meaning changes. Now the whole array must be equal:

db.movies.find(
  { genres: ["drama"] },
  { _id: 0, title: 1, genres: 1 }
)

Output:

[ { title: 'Okja', genres: [ 'drama' ] } ]

Only Okja matched, because its array is exactly ["drama"], with nothing else in it. Five movies contain drama, but only one has an array equal to ["drama"]. So a single value means "contains", and an array means "is equal to".

The $in operator from earlier also works on arrays. { genres: { $in: ["war", "music"] } } matches movies that contain at least one of those genres. To require several values together, use $all:

db.movies.find(
  { genres: { $all: ["drama", "music"] } },
  { _id: 0, title: 1 }
)

Output:

[ { title: 'Whiplash' } ]

Whiplash is the only movie with both genres.

In the exercise, find every movie whose genres include "thriller".