我在Mongo中有一个带有两个数组字段的文档:
field :app_usernames, type: Array
field :email_addresses, type: Array
我想创建一个函数,该函数将一组用户名和一组电子邮件地址用于搜索集合。踢球者是我希望它返回在数组中传递任何值的文档:
def find_people(usernames_to_search, emails_to_search)...
给定一个包含字段值的文档:
app_usernames = ['test1','test2','test3']
email_addresses = ['test1@test.com','test2@test.com']
我希望函数在通过数组参数搜索任何值时找到它。它应该在以下情况下返回此文档:
find_people nil,['test1@test.com']
find_people ['test3'],['test1@test.com']
find_people ['oldusername'],['test1@test.com']
最后一个似乎给我带来了麻烦。
到目前为止,我已经尝试了
.or(:app_usernames.in usernames_to_search, :email_addresses.in emails_to_search)
但无济于事。
答案 0 :(得分:5)
or
方法是通过个别条件列表调用的,以便它可以转为:
x.or(condition1, condition2)
进入MongoDB查询,如:
$or: [ condition1, condition2 ]
当你说:
.or(:app_usernames.in => usernames_to_search, :email_addresses.in => emails_to_search)
您传递给or
的参数有多少?答案是一个。你实际上是在说这个:
.or({ :app_usernames.in => usernames_to_search, :email_addresses.in => emails_to_search })
您需要自己添加大括号,以便Ruby不会将参数合并为一个哈希:
.or(
{ :app_usernames.in => usernames_to_search },
{ :email_addresses.in => emails_to_search }
)
或类似的东西:
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?)