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
您必须Bar
先返回Foo
嵌入对象的对象才能返回对象。
您可以查询顶级文档(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:嵌入某些元数据或聚合是在您真正需要时最好保留的优化
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句