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 = ['test1@test.com','test2@test.com']

      

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,['test1@test.com']
find_people ['test3'],['test1@test.com']
find_people ['oldusername'],['test1@test.com']

      

The latter seems to be causing me problems.

So far I have tried

.or(:app_usernames.in usernames_to_search, :email_addresses.in emails_to_search)

      

But to no avail.

+3


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(:app_usernames.in => usernames_to_search, :email_addresses.in => emails_to_search)

      



How many arguments are you passing in or

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

.or({ :app_usernames.in => usernames_to_search, :email_addresses.in => emails_to_search })

      

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

.or(
  { :app_usernames.in   => usernames_to_search },
  { :email_addresses.in => emails_to_search    }
)

      

Or something like this:

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

      

+5


source







All Articles