Row count per each distinct value of the field in Mongoose

Viewed 64

I have a schema like { reactionType: String, userName: String } (really simplified), and I want to count how many reactions of each type a given user has got. How do I do this with Mongodb and Mongoose?

I tried doing

MyModel.find({ userName: 'myUser' }).distinct('reactionType').count()

and the variations of this, but this seems to count the reaction types present for a given user, not the count of each reaction type for the user.

In case this helps to clarify what I want, in SQL I'd do something like

SELECT ReactionType, COUNT(1) FROM TheTable
WHERE UserName = 'myUser'
GROUP BY ReactionType

but how to translate this to Mongoose-speak?

I found this question that seems related, but it's solving a different problem and it didn't help given the above.

1 Answers

You need Aggregation Framework's $group operator:

MyModel.aggregate([
    {
        $match: { userName: 'myUser' }
    },
    {
        $group: {
            _id: "$reactionType",
            count: { $sum: 1 }
        }
    }
])
Related