mongodb count sub-document and list totals

后端 未结 2 1715
执念已碎
执念已碎 2021-01-23 03:36

In mysql, I have a query like:

mysql> SELECT user_id, count(user_id) as dup FROM addressbook GROUP BY user_id HAVING dup>20 ORDER BY dup;

2条回答
  •  清歌不尽
    2021-01-23 04:19

    Your id condition is blank and you do not have a where clause. I think this would be more like your sql query. Note that in case you have user_id in your users collection then you should replace $_id with $user_id

    db.users.aggregate( [
    
    { $match: { dub: { $gt: 20 } } },
     {
      $group: {
         _id: "$_id",
         count: { $sum: 1 }
       }
     }
    ])
    

提交回复
热议问题