【问题标题】:How would I grab all articles and order by number of comments? [duplicate]我如何获取所有文章并按评论数量排序? [复制]
【发布时间】:2012-05-15 04:05:08
【问题描述】:

可能重复:
How would I grab only articles with comments that were created 20 minutes ago?

使用 mongodb 和 mongoid。如何获取所有文章并按 cmets 数量排序?

class Article
  include Mongoid::Document

  has_many :comments
end

class Comment
  include Mongoid::Document

  belongs_to :article
end

【问题讨论】:

  • 添加一个计数器缓存(可能是this one),让自己轻松一点?
  • 我想过使用计数器缓存,但只是想看看是否有另一种方法来计算 cmets
  • 不,没有其他好方法。如果您希望它高效,则必须使用计数器缓存。请务必在计数器缓存字段上添加索引。
  • @KyleBanker 如果您将此添加为答案,我会很乐意选择它
  • 谢谢@ChristianFazzini。来吧,把它授予 theTRON :)

标签: ruby-on-rails ruby-on-rails-3 mongodb mongoid


【解决方案1】:

我不确定您打算排序的方向,因此我为两者都包含了索引 - 如果您不打算使用它,您应该删除一个,但这应该对您有用:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-15
    • 1970-01-01
    相关资源
    最近更新 更多