What is the efficient way of counting 2 level nested model (using mongoid or MongoDB in general)?
I have following data models. In which a Project embeds many ComponentDescriptor, and a ComponentDescriptor embeds many Statistic.
class Project
include Mongoid::Document
embeds_many :component_descriptors
field :status, :type => Integer
backgrounded :publish
end
class ComponentDescriptor
include Mongoid::Document
include Mongoid::Acts::Tree
embeds_many :statistics
embedded_in :project, :inverse_of => :com开发者_JS百科ponent_descriptors
end
class Statistic
include Mongoid::Document
field :statistics_type, :type => String
field :data, :type => String
field :playhead_time, :type => String
field :remote_ip, :type => String
field :user_agent, :type => String
embedded_in :component_descriptor, :inverse_of => :statistics
end
The question is what is the best way to count the total number of Statistic object in a Project.
One way I can think of is looping through each ComponentDescriptor and count the number of Statistics objects and then sum them up. But I think this is not efficient way.
Thank in advance.
If you can store the count field at the Project level that would be the most optimal and fastest way for you to obtain it.
精彩评论