首页 > 解决方案 > MongoDB中具有不同计数的双重聚合

问题描述

我们有一个存储日志文档的集合。

是否可以对不同的属性进行多个聚合?

最纯粹的文档看起来像这样:

{
   _id : int,
   agent : string,
   username: string,
   date : string,
   type : int,
   subType: int
}

通过以下查询,我可以轻松计算所有文档,并在特定时间段内按特定类型的子类型对它们进行分组:

db.logs.aggregate([
    {
        $match: {
            $and : [
                {"date" : { $gte : new ISODate("2020-11-27T00:00:00.000Z")}}
                ,{"date" : { $lte : new ISODate("2020-11-27T23:59:59.000Z")}}
                ,{"type" : 906}
            ]
        }
    },
    {
        $group: {
            "_id" : '$subType',
            count: { "$sum": 1 }
        }
    }
])

到目前为止,我的输出是完美的:

{
   _id: 4,
   count: 5
}

但是,我想要做的是添加另一个计数器,它也将添加不同的计数作为第三个属性。

假设我想在上面的结果集中附加第三个属性作为每个用户名的不同计数,所以我的结果集将包含 subType 作为 _id、文档总数的计数和表示用户名数量的第二个计数器有条目。就我而言,以某种方式创建文档的人数。

“伪结果集”看起来像:

{
   _id: 4,
   countOfDocumentsOfSubstype4: 5
   distinctCountOfUsernamesInDocumentsWithSubtype4: ?
}

这有什么意义吗?

请帮助我改进这个问题,因为当你不是 MongoDB 专家时很难用谷歌搜索它。

标签: mongodbmongodb-queryaggregation-framework

解决方案


您可以首先在最好的级别进行分组,然后执行第二次分组以达到您的需要:

db.logs.aggregate([
    {
        $match: {
            $and : [
                {"date" : { $gte : new ISODate("2020-11-27T00:00:00.000Z")}}
                ,{"date" : { $lte : new ISODate("2020-11-27T23:59:59.000Z")}}
                ,{"type" : 906}
            ]
        }
    },
    {
        $group: {
            "_id" : {
                subType : "$subType",
                username : "$username"
            },
            count: { "$sum": 1 }
        }
    },
    {
        $group: {
            "_id" : "$_id.subType",
            "countOfDocumentsOfSubstype4" : {$sum : "$count"},
            "distinctCountOfUsernamesInDocumentsWithSubtype4" : {$sum : 1}
        }
    }
])

这是我使用的测试用例: 测试用例

这是汇总结果: 汇总结果


推荐阅读