3

我在 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)

但无济于事。

4

1 回答 1

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?)
于 2014-10-10T00:26:23.790 回答