使用MongoDB中的聚合框架分组并计数

时间:2017-08-08 13:09:24

标签: mongodb mongoose aggregation-framework

我正在尝试使用计数对组内的数据进行分组。

{
        "_id" : ObjectId("59899846b5f5670840040b0b"),
        "client_id" : "merlin",
        "scope" : "eee",
        "user_id" : "u",
        "user_directory" : "kmdkcn",
        "createdAt" : ISODate("2017-08-08T10:53:58.816Z"),
        "open_url" : null,
        "__v" : 0
}
{
        "_id" : ObjectId("59899849b5f5670840040b0c"),
        "client_id" : "merlin",
        "scope" : "eee",
        "user_id" : "u",
        "user_directory" : "kmdkcn",
        "createdAt" : ISODate("2017-08-08T10:54:01.908Z"),
        "open_url" : null,
        "__v" : 0
}
{
        "_id" : ObjectId("5989984db5f5670840040b0d"),
        "client_id" : "merlin",
        "scope" : "eee",
        "user_id" : "y",
        "user_directory" : "kmdkcn",
        "createdAt" : ISODate("2017-08-08T10:54:05.280Z"),
        "open_url" : null,
        "__v" : 0
}
{
        "_id" : ObjectId("5989adb2d699bd211caa07ad"),
        "client_id" : "symphony",
        "scope" : "eee",
        "user_id" : "q",
        "user_directory" : "kmdkcn",
        "createdAt" : ISODate("2017-08-08T12:25:22.518Z"),
        "open_url" : null,
        "__v" : 0
}
{
        "_id" : ObjectId("5989adb8d699bd211caa07ae"),
        "client_id" : "symphony",
        "scope" : "eee",
        "user_id" : "w",
        "user_directory" : "kmdkcn",
        "createdAt" : ISODate("2017-08-08T12:25:28.954Z"),
        "open_url" : null,
        "__v" : 0
}
{
        "_id" : ObjectId("5989adbcd699bd211caa07af"),
        "client_id" : "symphony",
        "scope" : "eee",
        "user_id" : "q",
        "user_directory" : "kmdkcn",
        "createdAt" : ISODate("2017-08-08T12:25:32.753Z"),
        "open_url" : null,
        "__v" : 0
}
{
        "_id" : ObjectId("5989adc0d699bd211caa07b0"),
        "client_id" : "symphony",
        "scope" : "eee",
        "user_id" : "r",
        "user_directory" : "kmdkcn",
        "createdAt" : ISODate("2017-08-08T12:25:36.176Z"),
        "open_url" : null,
        "__v" : 0
}

我想要的是基于client_id对数据进行分组,并进一步基于user_id来获取文档的数量。

我试过这个: -

Logger.aggregate([
    { "$group": {
        "_id":  {client: "$client_id"},
        "count": { "$sum": 1 }
    }}
])

我得到: - 客户:梅林 数:3, 客户:交响乐, 数:4

但是如何在user_id的基础上对此进行分组。

我希望最终输出为: -

客户:梅林, 数:2, 客户:交响乐, 数:3

2 个答案:

答案 0 :(得分:0)

如果我正确理解了您的问题,那么您的数据库查询

 db.Logger.aggregate([
       { 
           $group : { 
                 _id : "$client_id", user : { $push: "$user_id" },
                 count: { $sum: 1 }
                    }
       }
  ])

答案 1 :(得分:0)

这是查询。

db.collection.aggregate([
    { "$group": {
        "_id":  {client: "$client_id" },
        "clientIdCount": { "$sum": 1 },
        "userids" : {"$addToSet" : "$user_id"}
    }
    },
    { "$project" : {"_id.client" : 1, "clientIdCount" : 1, numberOfUsers : {$size : "$userids"} }
    }
]);

<强>输出: -

如果您不想在输出中使用clientIdCount,只需将{1}}旁边的值从1更改为0。

clientIdCount