arjan kroon arjan kroon - 5 months ago 39
PHP Question

mongodb find query with OR and AND

I have the following if query.

if(($version[0] == 1)||($version[1] > 6)||($version[2]>=14 && $version[1] == 6))
echo "true";

Now I want this query translated to a mongodb query.
In the mongo collection I have the following entry:

"main_version" : 0,
"sub_version" : 6,
"build_version" : 14,
"module" : "Co2",
"active" : 1

When I try the following query I get a mongo error.

$where = array('$or' => array(
array('main_version'=> (int)$version[0]),
array('sub_version'=> array('$gt'=> (int)$version[1])),
array('$and' => array('build_version' => array('$gte'=> (int)$version[2])),
array('sub_version' => (int)$version[1]),
array('active'=> 1),

Error: Can't canonicalize query: BadValue and needs an array'

Does anybody know how to solve this query?


Well, worked in php 6 years back but I think your $and operator should accept array of queries,

something like array('$and' => array(array('build_version' => array('$gte'=> (int)$version[2])), array('sub_version' => (int)$version[1]))

'and' accepts array as you are doing for 'or' opeartor, here you are passing the query instead of array.