There is a typo in @miguel-savignano's response. According to Stackoverflow the "edit queue is full", which is why I didn't submit an edit.
Proper syntax:
Username.or({username: @username}).or({email: @email})
A more concise solution:
Username.or({username: @username}, {email: @email})
The Mongo selector will resolve to:
{"$or"=>[{"username"=>@username}, {"email"=>@email}]}
I found this question as I was trying to solve for creating "or" queries.
If you are looking to match a string or any one of an array of elements, then you will need to write a Mongoid query with the Mongo '$in' selector.
For example, you have a specific username and an array of emails. You would like to return all results where at least one of the fields matches either the username or one of the emails within the array.
@username = "jess"
@emails = ["[email protected]", "[email protected]", "[email protected]"]
User.or({username: ""}, {email: {'$in': @emails}})
The Mongo selector will resolve to:
{"$or"=>[{"first_name"=>""}, {"email"=>{:$in=>["[email protected]", "[email protected]", "[email protected]"]}}]}
- If you have
Users
with 2 of the 3 emails in your database, then the selector will return a count of 2.
- If you have a
User
with the username
"jess" and 3 additional Users
each with one of the given emails, then the selector will return a count of 4.