php and MongoDB: A ‘find $exists’ Mess of My Own

File this one under “Easy to Overlook … Duh”

Using php with MongoDB to process CSV files, and I want to find all the documents that do not have a particular field. (Inbound, I’m naming the fields a particular way. I’m also using ruby inbound, don’t ask, at least not yet…).

So, I want all documents where a field called UKNOWN_0064 does not exist. So I write:

$m = new Mongo();
$orders_in = $m->$mongo_db->$mongo_coll->find(array("UKNOWN_0064"=>array('$exists'=>'false')));

But I get everything that does have UKNOWN_0064 and none that don’t!

Anyway, you guessed it … the problem is

'$exists'=>'false'

Really needs to be

'$exists'=>false

And so the correct code is:

$m = new Mongo();
$orders_in = $m->$mongo_db->$mongo_coll->find(array("UKNOWN_0064"=>array('$exists'=>false)));

And here I had been feeling so smart to remember to use single tic to pass $exists – and yet blinded by my own ego to miss not enclosing the boolean false.

On a side note, if anyone knows a nicer way to play with MongoDB than all this array business, let me know. It’s clunky to me.

Facebook comments: