1
votes

I need to perform a query based on the value of some boolean fields. These fields may not exist in some documents, as they were added at a later stage.

I tested the query in the shell and worked ok:

db.product.find({$or: [{approved:true},{$and: [{approved:{$exists:false}}, {sold:{$ne:true}}]}]})

But trying to do the same with the PHP driver doesn't seem to work:

$condA = array('approved' => true);
$condB = array('approved' => array('$exists' => false), 'sold' => array('$ne' => true));

$query = array('pid' => $prodId, '$or' => array($condA, array('$and' => $condB)));

I tested some variants but I'm always getting this error in the log:

assertion 13086 $and/$or/$nor must be a nonempty array 

Any hint on what I might be doing wrong? Thanks in advance.

1
you don't need the $and at all, take out $and:[ ] and use {$or: [{approved:true},{approved:{$exists:false}, sold:{$ne:true} } ] } in the shell (you'll get the same thing) and then try that in corresponding PHP. - Asya Kamsky
Thank you, that was it! If you don't mind, would you like writing this as an answer so I can accept it? - Dan

1 Answers

1
votes

Since multiple "clauses" of a query are interpreted as "and" you don't need the $and in your query. If you take out $and:[ ] you end up with a simpler

{ $or : [ { approved : true }, { approved : {$exists:false}, sold : {$ne:true} } ] }

When you convert that into corresponding PHP that should work for you.