arjan kroon arjan kroon - 1 year ago 129
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?

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download