2011-05-23 45 views
2

我在MongoDB中使用MongoDB,並試圖在我們查看權重等之前設置一個基本的搜索作爲佔位符。any_of方法似乎是找到我的嵌入式文檔,但不是通過關係鏈接的。有誰知道any_of是否可以包含與db中其他文檔的關係,如果有的話,語法是什麼?Mongoid`any_of`可以包含外部文檔關係嗎?

belongs_to :principal #owner 
belongs_to :account #owner 

scope :search, ->(text) { any_of(
    {:description => /#{text}/i}, 
    {:name => /#{text}/i}, 
    {"entries.title" => /#{text}/i}, 
    {"entries.description" => /#{text}/i}, 
    {:tags => /#{text}/i}, 
    {"account.name" => /#{text}/i}, # Not finding by account name - because account isn't embedded? 
    {"principal.name" => /#{text}/i} # Not finding by principal name - because not embedded? 
)} 

回答

2

沒有,any_of是MongoDB的$or查詢相等的,所以本地的MongoDB會是這樣的:

db.collection.find(
{ "text" : 
    { "$or" : 
    [ { "account.name" => /#{text}/i }, { "principal.name" => /#{text}/i } ] 
    } 
}) 

Mongo的查詢只運行在單一的集合,所以要解決account.nameprincipal.name它們需要嵌入到文檔中的字段,例如

{ 
    text: 
    { 
     description: "...", 
     name: "...", 
     account: { name: "..." }, 
     principal: { name: "..." } 
    } 
} 
+0

正如我擔心的那樣。有沒有一種標準的方法來執行跨多個集合的Mongoid搜索,或者是否有必要在ruby控制器中放置邏輯? – 2011-05-23 02:29:47

+0

不是一個Mongoid專家,但你可能能夠使用關係 - http://mongoid.org/docs/relations.html - 失敗,需要從控制器運行單獨的查詢 – 2011-05-23 03:10:33

+0

感謝您的幫助。現在我正在整理兩個查詢的結果,這些查詢運行良好。 – 2011-05-23 03:12:40

相關問題