Search code examples
databasemongodbmongodb-querymongodb-shell

unknown top level operator: $eq


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".


Solution

  • 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" ]
        }
      }
    })