How can I make a query with or condition in Mongoid.
Asked
Active
Viewed 4,372 times
4
3 Answers
2
Here is the solution for "OR" query in mongoid.
if you want query like below
select * from user where id = 10 or name = 'hitesh';
in rails with mongoid then you have to write query like this
User.any_of({id: 10},{name: 'hitesh'}).first

hgsongra
- 1,454
- 15
- 25
0
@Simone Carletti is right but you also can use "mongo-style" notation:
# Ruby 1.9+
Person.where(last_name: {"$in" => ["Penn", "Teller"]})
#Ruby 1.9-
Person.where(:las_name => {"$in" => ["Penn", "Teller"]})
or simply
Person.where(:last_name.in => ["Penn", "Teller"])
upd
Conditions for two fields?
Person.where(:last_name.in => ["Penn", "Teller"], :first_name.in => ["Pedro", "Julio"])

fl00r
- 82,987
- 33
- 217
- 237
-
I need the or condition for two fields, lets say first name and last name – rajan sthapit Sep 29 '11 at 14:11
-
@fl00r do you know how to make this query belong an `OR` instead of an `AND` I mean, `last_name.in ... OR first_name.in: ...`? At the moment it does an `AND`. See this question for what I mean: http://stackoverflow.com/questions/23981407/how-do-i-find-an-object-whose-properties-foo-or-bar-equal-a-query-value – Jumbalaya Wanton Jun 01 '14 at 16:07