【问题标题】:mongodb count sub-document and list totalsmongodb count 子文档和列表总计
【发布时间】:2014-09-08 03:12:00
【问题描述】:

在 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 }

但这给了我所有地址簿条目的总数,我如何返回每个用户记录的总数并根据 mysql 输出列出?

非常感谢任何建议。

【问题讨论】:

  • 你的 $group _id 是空的,这就是聚合没有发生的原因。你能进一步解释你想要 mongo 明智的结果吗?

标签: mongodb


【解决方案1】:

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

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

输出:

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

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

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-08-04
      • 1970-01-01
      • 2022-11-24
      • 2016-05-12
      • 2021-06-13
      • 2011-10-02
      • 2015-03-12
      • 1970-01-01
      相关资源
      最近更新 更多