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?
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 } }
}
)