megas
megas

Reputation: 21791

Find active user

I'm using mongoid gem for storing events and users.

My goal is to find most active user (has biggest number of events).

Is there more correct way find active user for last hour then given solution?

User has_many Events

hash = Hash.new{ |h,k| h[k] = 0 }

Event.where(:created_at.gte => 1.hour.ago).each_with_object(hash) do |event, memo|
  memo[event.user_id] += 1
end.sort_by { |user_id,score| score }

Thanks

Upvotes: 0

Views: 75

Answers (1)

Asya Kamsky
Asya Kamsky

Reputation: 42352

You should let the database do the work for you by using aggregation framework to find this.

The pipeline would be something like:

db.events.aggregate({$match:{created_at:{$gt:<an-hour-ago>}}},
                    {$group:{_id:"$user_id", score:{$sum:1}}},
                    {$sort:{score:-1}}, {$limit:1} );

Upvotes: 2

Related Questions