found record through association

99 Views Asked by At

I have a modeling like this

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

I need to found the top 3 rooms that had most messages in the last 24 hours, but I have no idea from where to start.
maybe something with map/reduce?

3

There are 3 best solutions below

4
On BEST ANSWER

Try this using mongoid aggregation

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

There's definitely a better way to do this, but I think this code should work:

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

I solved with this

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])