Foo,Bar和Baz都是Mongoid系列。数据库中只有一些集合。
是否有更有效的方法来获取数据库中的所有数据?
Foo.all + Bar.all + Baz.all
答案 0 :(得分:1)
我当时并不知道一种查询多个集合的方法,我相信如果尝试这样做会破坏使用像MongoDB这样的NONSQL DB的目的。
但是,有一种方法可以在MongoDB中存档此行为。使用嵌入式文档。例如:
class Everything
include Mongoid::Document
include Mongoid::Timestamps
embeds_many :foos, class_name: 'Foo', inverse_of: :everything
embeds_many :bars, class_name: 'Bar', inverse_of: :everything
embeds_many :bazs, class_name: 'Bazs', inverse_of: :everything
end
class Foo
include Mongoid::Document
field :foo, type: String
embedded_in :everything, class_name: 'Everything', inverse_of: :foos
end
class Bar
include Mongoid::Document
field :bar, type: String
embedded_in :everything, class_name: 'Everything', inverse_of: :bars
end
class Bazs
include Mongoid::Document
field :baz, type: String
embedded_in :everything, class_name: 'Everything', inverse_of: :bazs
end
执行Everything.all
将检索Everything
中的所有文档以及一次调用中的所有嵌入文档。