我们有一个存储日志文档的集合。
是否可以对不同的属性进行多个聚合?
最纯粹的文档看起来像这样:
{
_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
}
但是,我想要做的是添加另一个计数器,这也将添加非重复计数作为第三个属性。
假设我想为上面的结果集附加第三个属性作为每个用户名的不同计数,因此我的结果集将包含子类型作为 _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}
}
}
])
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句