mongodb count sub-document and list totals

后端 未结 2 1714
执念已碎
执念已碎 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:02

    You can directly get the number of elements in the addressBook array field of each user by using $size:

    db.users.aggregate([
        {$project: {_id: 1, count: {$size: '$addressBook'}}}
    ])
    

    Output:

    {
        "result" : [ 
            {
                "_id" : ObjectId("540c83f9d901f28b921a328c"),
                "count" : 2
            }
        ],
        "ok" : 1
    }
    

    Note that the $size operator was introduced in MongodB 2.6.

    0 讨论(0)
  • 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 }
       }
     }
    ])
    
    0 讨论(0)
提交回复
热议问题