mongodb count子文档和列表总计

时间:2014-09-07 18:32:54

标签: mongodb

在mysql中,我有一个类似的查询:

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

会返回:

+---------+------+
| user_id | dup  |
+---------+------+
|    3052 |   21 |
|     996 |   23 |
|      46 |   25 |
|    2709 |   26 |
|    1756 |   28 |
|      43 |   30 |
|     224 |   30 |
|      98 |   32 |
|     289 |   35 |
|     208 |   40 |
|     888 |   43 |
|    4974 |   44 |
|      31 |   46 |
|     166 |   65 |
|    4560 |   99 |
|      85 |  112 |
|     280 |  124 |
|      27 |  166 |
|    2582 |  304 |
|      45 |  476 |
|    3830 |  932 |
|     232 | 1514 |
+---------+------+
22 rows in set (0.01 sec)

当我尝试在MongoDB中复制相同内容时,我无法正确地制定它!

我的收藏品类似

> db.users.find({ }).pretty();
{
    "_id" : ObjectId("540c83f9d901f28b921a328c"),
    "providers" : [
        "local"
    ],
    "loginAttempts" : 0,
    "company" : ObjectId("540c83f9d901f28b921a328a"),
    "group" : "company-admin",
    "firstName" : "Desmond",
    "emailVerified" : true,
    "addressBook" : [
        {
            "company" : "emilythepemily",
            "contact" : "Miss e m a Hudson",
            "address" : ObjectId("540c83f9d901f28b921a328d")
        },
        {
            "company" : "Hughes",
            "contact" : "Liam P Hughes",
            "address" : ObjectId("540c83f9d901f28b921a328e")
        },
...

这是我到目前为止所做的:

> db.users.aggregate({ $unwind : "$addressBook" }, { $group: { _id: '',count: { $sum: 1 }}})
{ "result" : [ { "_id" : "", "count" : 6705 } ], "ok" : 1 }

但是这给了我所有的addressBook条目,我如何返回每个用户记录的总数并按照mysql输出列出?

任何建议都非常感激。

2 个答案:

答案 0 :(得分:8)

您可以使用$size直接获取每个用户的addressBook数组字段中的元素数量:

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

输出:

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

请注意,$size运算符是在MongodB 2.6中引入的。

答案 1 :(得分:0)

您的ID条件为空,您没有where子句。    我认为这更像是你的SQL查询。请注意,如果您的用户集合中有user_id,则应将$ _id替换为$ user_id

db.users.aggregate( [

{ $match: { dub: { $gt: 20 } } },
 {
  $group: {
     _id: "$_id",
     count: { $sum: 1 }
   }
 }
])