Mongoid 'or' and 'in' - Query multiple arrays

I have a document in Mongo with two array fields:

field   :app_usernames,     type:  Array 
field   :email_addresses,   type:  Array


I would like to create a function that takes an array of usernames and an array of email addresses to search for a collection. The kicker is what I want it to return documents that have whatever values ​​passed in arrays:

def find_people(usernames_to_search, emails_to_search)...


So, a document with field values ​​is assigned:

app_usernames = ['test1','test2','test3']
email_addresses = ['','']


I want the function to find it when looking up any of these values ​​through the array parameters. He must return this document in the following cases:

find_people nil,['']
find_people ['test3'],['']
find_people ['oldusername'],['']


The latter seems to be causing me problems.

So far I have tried

.or( usernames_to_search, emails_to_search)


But to no avail.


source to share

1 answer

The method is or

designed to be called with a list of individual conditions so that it can do this:

x.or(condition1, condition2)


into MongoDB query like:

$or: [ condition1, condition2 ]


When you speak:

.or( => usernames_to_search, => emails_to_search)


How many arguments are you passing in or

? There is only one answer. You are actually saying this:

.or({ => usernames_to_search, => emails_to_search })


You need to add curly braces to prevent Ruby from folding the arguments into a single hash:

  {   => usernames_to_search },
  { => emails_to_search    }


Or something like this:

args = [ ]
args.push( => usernames_to_search) if(usernames_to_search.present?)
args.push( => emails_to_search)  if(emails_to_search.present?)
query = query.or(*args) if(args.present?)




All Articles