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

Popular posts from this blog

jquery - How do you format the date used in the popover widget title of FullCalendar? -

asp.net mvc - SSO between MVCForum and Umbraco7 -

Python Tkinter keyboard using bind -