Mongoid中如何快速查询多个集合?
How to quickly query multiple collections in Mongoid?
Foo、Bar、Baz都是Mongoid集合模型。数据库中只有这些集合。
是否有更高效的方式获取数据库中的所有数据?
Foo.all + Bar.all + Baz.all
我当时不知道查询多个集合的方法,我相信如果尝试这样做会破坏使用像 MongoDB.[=13= 这样的 NONSQL 数据库的目的]
但是,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
中的所有文档以及所有嵌入的文档。
Foo、Bar、Baz都是Mongoid集合模型。数据库中只有这些集合。
是否有更高效的方式获取数据库中的所有数据?
Foo.all + Bar.all + Baz.all
我当时不知道查询多个集合的方法,我相信如果尝试这样做会破坏使用像 MongoDB.[=13= 这样的 NONSQL 数据库的目的]
但是,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
中的所有文档以及所有嵌入的文档。