mongodb - 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 专家时很难用谷歌搜索它。
解决方案
您可以首先在最好的级别进行分组,然后执行第二次分组以达到您的需要:
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}
}
}
])
推荐阅读
- javascript - Javascript getFullYear 返回错误的年份
- java - 如何获取用户图像,存储它们,然后再渲染它们?
- javascript - 遍历深度嵌套的对象以生成 html optgroup/options
- java - Java:右移数字 1 不起作用
- c++ - 从系统调用分配的 C/C++ 中指针的奇怪值
- python - gcloud FileNotFoundError lib64
- python - 有没有更好的方法特别是使用 scipy.sparse 遍历稀疏矩阵的所有有效(正)条目?
- regex - 谷歌表单正则表达式至少 48 小时
- haskell - 为什么 runConduit 不发送所有数据?
- rx-swift - RxSwift - 如何从一个上游创建两个流