can I use combination of OR and AND in mongodb queries?
the code below doesn’t work as expected
db.things.find({
$and:[
{$or:[
{"first_name" : "john"},
{"last_name" : "john"}
]},
{"phone": "12345678"}
]});
database content:
> db.things.find();
{ "_id" : ObjectId("4fe8734ac27bc8be56947d60"), "first_name" : "john", "last_name" : "hersh", "phone" : "2222" }
{ "_id" : ObjectId("4fe8736dc27bc8be56947d61"), "first_name" : "john", "last_name" : "hersh", "phone" : "12345678" }
{ "_id" : ObjectId("4fe8737ec27bc8be56947d62"), "first_name" : "elton", "last_name" : "john", "phone" : "12345678" }
{ "_id" : ObjectId("4fe8738ac27bc8be56947d63"), "first_name" : "eltonush", "last_name" : "john", "phone" : "5555" }
when querying the above query – i get nothing!
> db.things.find({$and:[{$or:[{"first_name" : "john"}, {"last_name" : "john"}]},{"phone": "12345678"}]});
>
I’m using mongo 1.8.3
I believe $and is only supported in MongoDB v2.0+. I’m surprised that the console accepted the expression in the first place. I’ll try to recreate against a 1.8 server I have.
Also check 10Gen’s Advanced Query Documentation for
$and.Update
I entered your sample data into both a v1.8x and v2.0x MongoDB server. The query works on the v2.0x and fails on the v1.8x. This confirms my (and Miikka’s) suspicions that the problem is with
$andand your server version.I found a (arguably) clever workaround for this on the Web here. I hope this helps.
-SethO