Reputation: 55
Trying to do a simple mongodb query that drives me mad.... I have the following table/db:
[_id] => MongoId Object (
[$id] => 4f22efa1ef9dec8495b374bc
)
[h1] => a
[h2] => b
[h3] => c
[_id] => MongoId Object (
[$id] => 4f22efa1ef9dec8495b374bd
)
[h1] => d
[h2] => e
[h3] => f
Using the mongo tool command line and typing:
db.things.find({$or: [{'h1' : 'a'},{'h1': 'd'}]})
I get:
{ "_id" : ObjectId("4f22efa1ef9dec8495b374bc"), "h1" : "a", "h2" : "b", "h3" : "c" }
{ "_id" : ObjectId("4f22efa1ef9dec8495b374bd"), "h1" : "d", "h2" : "e", "h3" : "f" }
Which is fine. However trying doing the same from PHP, I get nothing ??:
$m = new Mongo();
$db = $m->selectDB('testdb');
$collection = new MongoCollection($db, 'things');
$query = array( '$or' => array( array('h1' => 'a')),
array('h1' => 'd'));
$cursor = $collection->find($query);
I do not see what I am doing wrong, but I have tried anything (or I think so) for 3 days now and it will not work. If I do queries using '>=' '<=' '<>' '<' '>' it works fine but using '=' as in this case it does not.
Thanks for your effort !
Upvotes: 3
Views: 316
Reputation: 66358
You're better off using $in for your given example, i.e.:
$collection->find(array('h1' => array('$in' => array('a', 'd'))));
As to why your query doesn't work - you're not using $or correctly (or infact, at all). This is the query you've put in the question reformatted:
$query = array(
'$or' => array(
array('h1' => 'a')
),
array('h1' => 'd')
);
Whereas you would need:
$query = array(
'$or' => array(
array('h1' => 'a'),
array('h1' => 'd')
)
);
If you have a look in the mongodb error log most likely it says something about that illegal loose top-level array in the conditions.
Upvotes: 3