2014-10-09 80 views
3

我在蒙戈一個文件具有兩個陣列的字段:Mongoid「或」和「中」 - 查詢多個陣列

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 = ['[email protected]','[email protected]'] 

通過數組參數搜索任何這些值時找到它。它應該在下列情況下返回此文檔:

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

最後一個似乎給我造成麻煩。

到目前爲止,我已經試過

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

,但無濟於事。

回答

5

or方法是爲了與個人條件的列表被調用,以便它可以把這樣的:到MongoDB的查詢關鍵詞,比如

x.or(condition1, condition2) 

$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 }) 

你需要自己添加大括號,使紅寶石不垮的參數爲一個哈希:

.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?) 
+0

完美!非常感謝。 – JimmyP 2014-10-10 05:51:29