MongoError: unknown top level operator: $in. If you have a field name that starts with a '$' symbol, consider using $getField or $setField

MongoError: unknown top level operator: $in. If you have a field name that starts with a ‘$’ symbol, consider using $getField or $setField.
at MessageStream.messageHandler (/app/node_modules/mongoose/node_modules/mongodb/lib/cmap/connection.js:299:20)
at MessageStream.emit (node:events:513:28)
at processIncomingData (/app/node_modules/mongoose/node_modules/mongodb/lib/cmap/message_stream.js:144:12)
at MessageStream._write (/app/node_modules/mongoose/node_modules/mongodb/lib/cmap/message_stream.js:42:5)

MongoError: unknown top level operator: $in

You’re likely trying to use the $in operator directly without wrapping the operation correctly to perform either a find or and aggregate.

Can you share the code where you’ve specified an $in?

I have function like this that returns the query:
function getMovieFilterQuery(filters = {}){
  const query = {}

  if (filters.moviesIds !== undefined) {
      query.movieId = { $in: filters.movieIds };
    }

  return query;
}

@ramanjaneya_karnati you’ll likely need to trace the caller of getMovieFilterQuery to see how the function result is being passed to a query, but given the error you shared you’re likely sending a command similar to the following to the server:

db.foo.find({ $in: [ 'movie1', 'movie2' ] })

The server is expecting you to send:

db.foo.find({ movieId: { $in: [ 'movie1', 'movie2' ] }})

Stepping through your logic should surface the issue pretty quickly.

1 Like