我将MongoDB与Mongoid一起使用,并尝试在查看权重等之前,将基本搜索作为占位符放置到位。any_of方法似乎在查找我的嵌入文档,但不是那些通过关系链接的文档。是否有人知道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?
)}

最佳答案

不,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: "..." }
    }
}

关于ruby-on-rails-3 - Mongoid`any_of`可以包括使用外部文档关系吗?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/6092085/

10-11 03:54
查看更多