Reputation: 7279
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?
Upvotes: 2
Views: 92
Reputation: 7279
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])
Upvotes: 2
Reputation: 681
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 } }
}
)
Upvotes: 2
Reputation: 3516
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)
Upvotes: -1