Row count per each distinct value of the field in Mongoose

﹥>﹥吖頭↗ 提交于 2021-01-27 22:00:44

问题


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:


You need Aggregation Framework's $group operator:

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


来源:https://stackoverflow.com/questions/61180417/row-count-per-each-distinct-value-of-the-field-in-mongoose

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!