Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Logical OR for two different fields in $where queries in mongodb

Tags:

mongodb

How do you do a query like the one below, where I want hotels in London OR hotels which have hilton in their name?

This query db.hotels.find({$where : "name = /hilton/i || city = /london/i"})

gives such an error error: { "$err" : "$where compile error" }

Both queries separately work ok: db.hotels.find({$where : "city = /london/i"}) db.hotels.find({$where : "name = /hilton/i"})

like image 917
Piotr Zolnierek Avatar asked Dec 22 '09 10:12

Piotr Zolnierek


2 Answers

Now, that mongodb supports $or condition, you can do this like:

db.hotels.find( { $or: [ { name: /hilton/i }, 
                         { city: /london/i } 
                       ] 
              } );
like image 195
rsmoorthy Avatar answered Nov 15 '22 09:11

rsmoorthy


Try this:

db.hotels.find({
    $where: "/london/i.test(this.city) || /hilton/i.test(this.hotel)"
})

NOTE As far as I understand $where does a per-document evaluation, so it can be pretty slow. If you'd have a single attribute, I'd suggested smth like

db.hotels.find({name: /(hilton|london)/i})
like image 27
Alexander Azarov Avatar answered Nov 15 '22 09:11

Alexander Azarov