CodyBugstein
CodyBugstein

Reputation: 23312

In a mongodb aggregation query, how can I check if field's value matches one in a given array?

I am writing a MongoDB query, using aggregate.

I want to find all results that are matches based on given music preferences.

For example, here is a sample of my code

matchingGenres = ["CLASSIC_ROCK", "HEAVY_METAL", "POP"];
dbquery = [
        {
            $project:{
             ....
            }
        },
        {
            $match: { 
                $and: [
                    {genre: ?????}, // match if genre is in the array matchingGenres
                ...
                ]
         }
]

How do I match only if the documents value for the genre field is in the array matchingGenres?

Upvotes: 0

Views: 77

Answers (1)

mickl
mickl

Reputation: 49945

You can use $in operator to match against multiple values. For example:

{
   $match: {
      genre: { $in: ["CLASSIC_ROCK", "HEAVY_METAL", "POP"] }
   }
}

Upvotes: 1

Related Questions