I’m having trouble with this MongoDB query using PHP array syntax. This is a direct version of the query I want to use.
db.collection.find({
$or: [
{$and : [{X:1}, {X: {$gt: 100}}]},
{$and : [{X:2}, {X: {$lt: 100}}]}
]
});
Note: The real query is more complicated, this is just an example.
I wasn’t able to find some examples describing this kind of query in PHP. The best I’ve come up was this:
$query = array(
'$or' => array(
array(
'$and' => array(
array('X' => 1),
array('X' => array('gt' => 100))
)
),
array(
'$and' => array(
array('X' => 2),
array('X' => array('lt' => 100))
)
),
)
);
$this->db->collection->find($query);
But this query doesn't return any results.
Obviously we can't remove $and
from the array because we can't have duplicate keys in PHP array.
I don't want to use JavaScript expressions because the speed is critical.
UPDATE: As Alexander Azarov pointed out in comments, my original query can be written differently. I've updated the question with the properly used $and
query.
$and
here.{X:1, Y: {$all: [5,6,7]}}
should work. – Infantry$and
exists for this king of thing:db.foo.find( { $and: [ { a: 1 }, { a: { $gt: 5 } } ] } )
– Harker