通过协会找到记录

时间:2014-12-23 13:23:07

标签: ruby-on-rails mongodb ruby-on-rails-4 mongoid moped

我有这样的模型

class Room
  include Mongoid::Document
  field :name, type: String
  has_many :messages
end

class Message
  include Mongoid::Document
  field :content, type: String
  belongs_to :room
end

我需要找到过去24小时内收到最多邮件的前3个房间,但我不知道从哪里开始。
也许有map / reduce的东西?

3 个答案:

答案 0 :(得分:2)

使用mongoid aggregation

尝试此操作
Room.collection.aggregate(
  {
    "$match" => {"$messages.created_at" => {"$gte" => 1.day.ago}},
    "$group" => { 
      _id: '$messages', count: {"$sum" => 1}
    },
    { "$sort" => { count: -1 } }
  }
)

答案 1 :(得分:2)

我用这个解决了

match = { "$match" => { "created_at" => { "$gte" => 1.day.ago } } }
group = { "$group" => { _id: '$room_id', count: {"$sum" => 1 } } }
sort = { "$sort" => { count: -1 } }
limit = { "$limit" => 3 }

Message.collection.aggregate([match, group, sort, limit])

答案 2 :(得分:-1)

肯定有更好的方法可以做到这一点,但我认为这段代码应该有效:

Room.select("rooms.*, count(messages) as count").joins(:messages).where("messages.created_at < ?", 1.day.ago).group("rooms.id").order("count DESC").limit(3)