Tuesday, September 6, 2011

Uncaught exception 'MongoCursorException' with message 'invalid query'

Another nasty MongoDb exception that's hard to detect if everything had been working earlier. The more you have progressed without noticing this, the more you will have to fix which could have been prevented. So, if you landed here, most likely you have the same problem I had.

What's the problem?

Well, it's actually trivial if you know what you are looking for. It's just that the mongo server is complaining to have received a wrong parameter for $in which requires an ARRAY data type. The error message is vague I know and can easily put you in circles. Hopefully, a better verbiage is placed if my request is granted. My mongodb version is 1.8.3.

    [errmsg] => exception: invalid query
    [code] => 12580
    [ok] => 0

It should be {"username":{"$in":['user1','user2']}}.

The prevention/fix; much like how you do it when querying a resource, database, api or another application, sanitize your query first by checking if you are passing a valid value, in this case an array by using something like:

An IF condition:

if (!empty($value) && is_array($value)) {
      //its safe to query now
     $mongo->query(array('value' => array('$in' => $value)));

Or a ternary operator:

$value = !empty($value) && is_array($value) ? $value : array();
$mongo->query(array('value' => array('$in' => $value)));

Hope this helps.
  • Related Links Widget for Blogspot


Anonymous said...

Thanks this solved my issue.

Anonymous said...

Thanks this solved my issue. One of the arguments I passed to $in was incorrect.