0

Sample of my database:

{
  name: 'The Perks of Being a Wallflower'
  genres: ['Drama', 'Romance']
  rating: 8
}, 
{
  name: 'The Edge of Seventeen'
  genres: ['Drama', 'Comedy']
  rating: 7.3
},
{
  name: 'Little Women',
  genres: ['Drama', 'Romance']
  rating: 7.8
}

I want to project the first element of the genres array if it's Comedy or Romance.
I tried this :

db.shows.find(
  {},
  { genres: { $elemMatch: { $or: [{ $eq: 'Drama' }, {$eq: 'Comedy'}] } } }
);

But it gives me this error "unknown top level operator: $eq".

Tushar Gupta - curioustushar
  • 58,085
  • 24
  • 103
  • 107
Moaaz Bhnas
  • 1,010
  • 7
  • 18
  • 36

1 Answers1

2

Use $in

The $in operator selects the documents where the value of a field equals any value in the specified array. To specify an $in expression, use the following prototype:

Demo - https://mongoplayground.net/p/MAuWUeP9GIE

db.collection.find({
  genres: {
    $elemMatch: {
      "$in": [ "Drama", "Comedy" ]
    }
  }
})

Demo - https://mongoplayground.net/p/JJJkoHuz_DZ

db.collection.find({},
{
  genres: {
    $elemMatch: {
      "$in": [ "Drama", "Comedy" ]
    }
  }
})
Tushar Gupta - curioustushar
  • 58,085
  • 24
  • 103
  • 107