mongodb - Sort by number of subdocuments mongoid -
i have model person
has many comments
how sort people collection number of comments
something
person.desc(:"comments.count")
you can't work 2 collections @ once need in person
can can sort on. usual approach use counter cache cache number of comments in each person
. you'd have this:
class person include mongoid::document has_many :comments end class comment include mongoid::document belongs_to :person, :counter_cache => true end
the :counter_cache => true
option belongs_to
add comments_count
field person
contain cached number of comments.
once have counter cache, can say:
person.desc('comments_count')
to sorting.
you'll need initialize counters hand using person.reset_counters
or person#reset_counters
things started.
Comments
Post a Comment