sum with group in mongoid

aggregation-framework, mongodb, mongoid, ruby, ruby-on-rails

Solution

You would be better off using the aggregation framework method from MongoDB in the moped syntax. Other methods like `.group_by` are legacy JavaScript engine wrappers that are much slower at evaluating results:

LikeCount.collection.aggregate([
    {"$group" => {
        "_id" => "$account_id",
        "likes" => {"$sum" => "$like_count"}
    }},
    {"$sort" => { "likes" => -1}}
])

That uses the `$group` pipeline stage in order to aggregate results by the given `_id` key, and the `$sort` pipeline orders the results, in this case in a "descending" order.

The aggregation framework is implemented in native code and is much faster at processing results.

Problem

I am new in mongoid and mongodb. I have a model name `like_count(account_id, create_at, updated_at, like_cnt)`. I need sum of the each accounts like count in a sorted order. I have tried something like ``` LikeCount.group_by(&:account_id).sum(:like_cnt) ``` But seems like it is wrong.

Original source