可能重复:
How would I grab only articles with comments that were created 20 minutes ago?
使用mongodb和mongoid。如何根据评论数量获取所有文章和订单?
class Article
include Mongoid::Document
has_many :comments
end
class Comment
include Mongoid::Document
belongs_to :article
end
答案 0 :(得分:1)
我不确定你打算排序的方向,所以我包括了两者的索引 - 你应该删除一个,如果你不打算使用它,但这应该为你做的伎俩: / p>
class Article
include Mongoid::Document
field :comments_count, :type => Integer, :default => 0
index [[ :comments_count, Mongo::ASCENDING ]]
index [[ :comments_count, Mongo::DESCENDING ]]
has_many :comments
before_save :update_comments_count
protected
def update_comments_count
self.comments_count = self.comments.count
end
end