ruby-on-rails - mongoid - 查询嵌入式文档

标签 ruby-on-rails mongodb mongoid

class Foo
  include Mongoid::Document
  field :name, type: String
  embeds_many :bars
end

class Bar
  include Mongoid::Document
  field :name, type: String
  embedded_in :foo
end

有没有一种方法可以在这里查询所有的bars?在 AR 中,我会执行类似 Bar.where(name: 'something') 之类的操作 - 只需给我所有符合某些条件的条形即可。

就目前而言,我只能查询单个 foo 上的特定柱。 `Foo.first.bars.where(name: 'something')。我知道 mongoDB 没有连接,所以...我很好奇该怎么做。

我准备好一起失去 Foo 并做类似的事情:

class Bar
  include Mongoid::Document
  field :foo_name, type: String
  field :name, type: String
end

最佳答案

如果不首先返回嵌入的 Foo 对象,则无法返回 Bar 对象。

您可以查询顶级文档 (Foo) 作为嵌入文档的匹配项。

foo = Foo.create(:name => 'foo1')
foo.bars << Bar.new(:name => 'bar1')

Foo.where(:'bars.name' => 'bar1').first
=> #<Foo _id: 53c4a380626e6f813d000000, name: "foo1">

然后,一旦您拥有与某个嵌入条匹配的 Foos,您就可以通过另一个查询找到您正在寻找的条(它只映射到 Array#findArray#select

foo.bars << Bar.new(:name => 'bar2')
Foo.where(:'bars.name' => 'bar1').first.bars.where(:name => 'bar2').first
=> #<Bar _id: 53c4a380626e6f813d000001, name: "bar2">

更新: 如果您在父文档上下文之外查询嵌入文档,我建议不要使用嵌入文档。当您嵌入文档时,您是在说“我不打算让文档单独存在”。如果您发现自己直接查询它,则放弃嵌入。嵌入很诱人,但通常您不需要/不需要它。

注意:我已经去嵌入了超过 1 亿个条目,这是一个漫长而忙碌的过程。

注意2:嵌入一些元数据或聚合是一种优化,最好在您真正需要的时候保留

关于ruby-on-rails - mongoid - 查询嵌入式文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24749312/

相关文章:

sql - 高级计数和加入 Rails

javascript - 允许您在 html 中粘贴小型 JavaScript 脚本的网站如何跟踪您的网站?

ruby-on-rails - 如何在 Rails 上实现 cookieless flash 消息?

node.js - Write关注在node.js的mongodb native 驱动程序中插入文档

以 id 为键的 MongoDB 组和求和

json - as_json 运行速度非常慢(Mongoid + Sinatra)

ruby-on-rails - 如何使用 Nokogiri 和 XPath 或 CSS 选择器选择一大块 HTML?

node.js - 使用 GridFSBucket openDownloadStream 时出现文件未找到错误

ruby - Mongoid 嵌入式集合响应 :find

ruby-on-rails - 更改 Mongoid 中的字段类型而不丢失数据