just_user
just_user

Reputation: 12067

mongodb get users with most liked posts

If I have a collection with documents looking more or less like this:

{
"_id": "52c06c86b78a091f26000001",
"desc": "Something somethingson",
"likes": [
    {
        "user_id": "52add4f4344e8ca867000001",
        "username": "asd",
        "created": 1390652212592
    },
    {
        "user_id": "52add4f4344e8ca867000001",
        "username": "asd",
        "created": 1390652212592
    }
],
"user_id": "52add4f4344e8ca867000001",
"username":"username"
}

Could I with mongodb (using nodejs & express) get a list of 10 users with the most liked posts?

I'm thinking it should be possible to do this Map-Reduce or with Aggregate, by grouping all posts by "user_id" and then count the total amount of items in the "likes" array. And then get the top 10 "user_id"s from that.

I'm guessing this is possible. Only problem is that I dont get the examples from the mongo website enough to put together my own thing.

Could anyone show me an example of doing this, or at least tell me its impossible if it is. =)

Upvotes: 1

Views: 1964

Answers (3)

heinob
heinob

Reputation: 19474

Yes, it is possible:

db.coll.aggregate([
    {
        $unwind: "$likes"
    },
    {
        $group: {
            _id: "$user_id", 
            likesPerUser: {
                $sum:1
            }
        }
    }
    {
        $sort: {
            likesPerUser: -1
        };
    }
    {
        $limit: 10
    }
])

Upvotes: 2

blacelle
blacelle

Reputation: 2217

If you need to count the number of likes element per parent user, you can do the following:

http://mongotry.herokuapp.com/#?bookmarkId=52fb8c604e86f9020071ed71

[
{
    "$unwind": "$likes"
},
{
    "$group": {
        "_id": "$user_id",
        "likesPerUser": {
            "$sum": 1
        }
    }
},
{
    "$sort": {
        "likesPerUser": -1
    }
},
{
    "$limit": 10
}
]

Else if you need the number of liked user-id, counting 1 per sub-document cross all parents, you can do the following:

http://mongotry.herokuapp.com/#?bookmarkId=52fb8cf74e86f9020071ed72

[
{
    "$unwind": "$likes"
},
{
    "$group": {
        "_id": "$likes.user_id",
        "likesPerUser": {
            "$sum": 1
        }
    }
},
{
    "$sort": {
        "likesPerUser": -1
    }
},
{
    "$limit": 1
}
]

Upvotes: 0

Rishi
Rishi

Reputation: 268

Try that out...

db.collection.aggregate([
  {$unwind: "$likes"},
  {$group: {_id: "$user_id", likesCount: {$sum: 1}}},
  {$sort: {likesCount: -1}},
  {$limit: 10},
  {$project: {_id: 1}}
])

See this tutorial.

Upvotes: 6

Related Questions