MongoDB:在$group之后使用$setWindowFields



我有大约30,000个实例,每个实例都有一个给定的时间戳和大陆。

我想运行一个查询,按月分组数据,每月返回每个定义的大陆(例如"欧洲"、"亚洲")的实例计数,然后计算每个大陆的累计计数。

这个查询是针对Grafana仪表板的,所以它需要是一个聚合操作。

目前,我的查询返回给定行的大陆计数,而不是该行及其前行的累积计数。

。如果欧洲是"10",则无论之前发生了什么,累计计数也将为"10"。

查询:

targets.targets.aggregate([
{
$match: {
"status.isError": false,
}
},
{
$group: {
_id: {
$dateToString: {
format: "%Y-%m-01T00:00:00.000Z", date: { $toDate: "$date_posted" }
}
},
Europe: {
$sum: {
$cond: [
{ $eq: ["$continent", "Europe"] },
1,
0
]
}
}
}
},
{
$project: {
_id: 1,
Europe: 1
}
},
{
$sort: {
"_id": 1
}
},
{
$addFields: {
time: { $dateFromString: { dateString: "$_id" } }
}
},
{
$project: {
_id: 1,
time: 1,
Europe: 1
}
},
{
$setWindowFields: {
partitionBy: "$time",
sortBy: { "time": 1 },
output: {
cumulativeCount: {
$sum: "$Europe"
}
}
}
}
])

如果我在分组之前尝试$setWindowFields,查询错误,因为排序超过内存限制。

试试这样:

db.collection.aggregate([
{$match: {"status.isError": false}},
{$group: {
_id: {
date: {
$dateTrunc: {
date: "$date_posted",
unit: "day"
}
},
continent: "$continent"
},
count: {$sum: 1}
}},
{$project: {
_id: 0,
continent: "$_id.continent",
date: "$_id.date",
count: 1
}},
{$setWindowFields: {
partitionBy: "$continent",
sortBy: {"date": 1},
output: {
cumulativeCount: {
$sum: "$count",
window: {documents: ["unbounded", "current"]}
}
}
}}
])

看看它在操场的例子中是如何工作的

最新更新