What is the correct way to do a HAVING in a MongoDB GROUP BY?

前端 未结 1 1522
夕颜
夕颜 2020-12-03 04:55

For what would be this query in SQL (to find duplicates):

SELECT userId, name FROM col GROUP BY userId, name HAVING COUNT(*)>1

I perform

相关标签:
1条回答
  • 2020-12-03 05:21

    New answer using Mongo aggregation framework

    After this question was asked and answered, 10gen released Mongodb version 2.2 with an aggregation framework. The new best way to do this query is:

    db.col.aggregate( [
       { $group: { _id: { userId: "$userId", name: "$name" },
                   count: { $sum: 1 } } },
       { $match: { count: { $gt: 1 } } },
       { $project: { _id: 0, 
                     userId: "$_id.userId", 
                     name: "$_id.name", 
                     count: 1}}
    ] )
    

    10gen has a handy SQL to Mongo Aggregation conversion chart worth bookmarking.

    0 讨论(0)
提交回复
热议问题