[英]mongoid - querying embedded docs
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(名字:'某事')。 我知道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#find
或Array#select
foo.bars << Bar.new(:name => 'bar2')
Foo.where(:'bars.name' => 'bar1').first.bars.where(:name => 'bar2').first
=> #<Bar _id: 53c4a380626e6f813d000001, name: "bar2">
更新:如果您要查询父文档上下文中的嵌入式文档,我建议不要使用嵌入式文档。 当您嵌入文档时,您说“我不打算将文档存在于自己的文档中”。 如果你发现自己直接查询它,那么就放弃嵌入。 它很容易嵌入,但通常你不需要/需要它。
注意:我已经去嵌入了100M +条目,这是一个漫长的过程。
注意2:嵌入一些元数据或聚合是一种优化,最好在您真正需要的时候保留
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.