如何在mongodb聚合中同时计算文档总数和分组计数?
我在mongodb集合中有一个名为如何在mongodb聚合中同时计算文档总数和分组计数?,mongodb,aggregation,Mongodb,Aggregation,我在mongodb集合中有一个名为visitorsessionlike的数据集 {ip : 192.2.1.1,country : 'US', type : 'Visitors',date : '2019-12-15T00:00:00.359Z'}, {ip : 192.3.1.8,country : 'UK', type : 'Visitors',date : '2019-12-15T00:00:00.359Z'}, {ip : 192.5.1.4,country : 'UK', type :
visitorsession
like的数据集
{ip : 192.2.1.1,country : 'US', type : 'Visitors',date : '2019-12-15T00:00:00.359Z'},
{ip : 192.3.1.8,country : 'UK', type : 'Visitors',date : '2019-12-15T00:00:00.359Z'},
{ip : 192.5.1.4,country : 'UK', type : 'Visitors',date : '2019-12-15T00:00:00.359Z'},
{ip : 192.8.1.7,country : 'US', type : 'Visitors',date : '2019-12-15T00:00:00.359Z'},
{ip : 192.1.1.3,country : 'US', type : 'Visitors',date : '2019-12-15T00:00:00.359Z'}
我正在使用这个mongodb
aggregation
[{$match: {
nsp : "/hrm.sbtjapan.com",
creationDate : {
$gte: "2019-12-15T00:00:00.359Z",
$lte: "2019-12-20T23:00:00.359Z"
},
type : "Visitors"
}}, {$group: {
_id : "$country",
totalSessions : {
$sum: 1
}
}}, {$project: {
_id : 0,
country : "$_id",
totalSessions : 1
}}, {$sort: {
country: -1
}}]
使用上面的聚合
我得到的结果如下
[{country : 'US',totalSessions : 3},{country : 'UK',totalSessions : 2}]
但我也会计算总访客数以及结果,比如totalVisitors:5
如何在
mongodb聚合中做到这一点?您可以使用$facet
聚合阶段计算总访客以及单个通道中按国家/地区划分的访客:
db.visitorsSession.aggregate( [
{
$match: {
nsp : "/hrm.sbtjapan.com",
creationDate : {
$gte: "2019-12-15T00:00:00.359Z",
$lte: "2019-12-20T23:00:00.359Z"
},
type : "Visitors"
}
},
{
$facet: {
totalVisitors: [
{
$count: "count"
}
],
countrySessions: [
{
$group: {
_id : "$country",
sessions : { $sum: 1 }
}
},
{
$project: {
country: "$_id",
_id: 0,
sessions: 1
}
}
],
}
},
{
$addFields: {
totalVisitors: { $arrayElemAt: [ "$totalVisitors.count" , 0 ] },
}
}
] )
输出:
{
"totalVisitors" : 5,
"countrySessions" : [
{
"sessions" : 2,
"country" : "UK"
},
{
"sessions" : 3,
"country" : "US"
}
]
}
您最好使用两个查询来执行此操作
为了节省两个db往返,可以使用以下聚合来计算文档,IMO有点冗长(如果文档非常大,成本可能会很低)
想法:是在顶部有一个用于计数文档并使用和$$ROOT
保存原始文档的列表。然后在其他匹配/筛选操作之前,创建原始文档的数组
db.collection.aggregate([
{
$group: {
_id: null,
docsCount: {
$sum: 1
},
originals: {
$push: "$$ROOT"
}
}
},
{
$unwind: "$originals"
},
{ $match: "..." }, //and other stages on `originals` which contains the source documents
{
$group: {
_id: "$originals.country",
totalSessions: {
$sum: 1
},
totalVisitors: {
$first: "$docsCount"
}
}
}
]);
样品O/p:
这个查询运行得很好,但我得到的结果与您提到的不完全相同。我得到的结果是这样的totalVisitors:[{count:5},countrySessions:[{sesions:2,country:'UK'},{sesions:3,country:'US'}]
我想你在没有最后一个$addFields
阶段的情况下运行了这个查询;将它包括进来,并得到答案中的结果。
[
{
"_id": "UK",
"totalSessions": 2,
"totalVisitors": 5
},
{
"_id": "US",
"totalSessions": 3,
"totalVisitors": 5
}
]