Mongoid`any_of`可以包括使用外部文档关系吗?

时间:2011-05-23 01:50:20

标签: ruby-on-rails-3 mongodb mongoid

我正在使用MongoDB和Mongoid,并在我们查看加权等之前尝试将初步搜索作为占位符。any_of方法似乎是找到我的嵌入式文档而不是关联链接的文档。有谁知道any_of是否可以包含与db中其他文档的关系,如果是,那么语法是什么?

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

1 个答案:

答案 0 :(得分: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: "..." }
    }
}