mongodb - 如何减去时间序列元素以获得与之前日期的差异?
问题描述
我正在尝试在 Mongo-Atlas 中构建仪表板图表。表格应在 x 轴上显示日期,在 y 轴上显示 _id。值应该是与前一天的计数差异。
我有一个包含数据点的集合,例如:
_id: "someName"
timestamp: 2019-09-05T06:24:24.689+00:00
count: 50
_id: "someName"
timestamp: 2019-09-04T06:24:24.689+00:00
count: 40
...
目标是获得计数与之前数据点的差异。有同名。
_id: "someName"
timestamp: 2019-09-05T06:24:24.689+00:00
count: 50
difference: 10
_id: "someName"
timestamp: 2019-09-04T06:24:24.689+00:00
count: 40
difference: 17
...
这样我就可以制作一个列出差异的表格
到目前为止,我创建了一个聚合管道
[
{$sort: {
"timestamp": -1
}},
{$group: {
_id: "$_id",
count: {
$push: { count: "$count", timestamp: "$timestamp" }
}
}},
{$project: {
_id: "$_id",
count: "$count",
countBefore: { $slice: [ "$count", 1, { $size: "$count" } ] }
}}
]
我希望减去 count 和 countBefore 这样我得到一个包含数据点的数组和差异......
所以我尝试遵循:
{$project: {
countDifference: {
$map: {
input: "$countBefore",
as: "before",
in: {
$subtract: ["$$before.count", "$count.count"]
/*"$count.count" seems to be the problem, since an integer works*/
}
}
}
}
}
Mongo Atlas 仅显示“发生未知错误”
我很高兴得到一些建议:)
解决方案
以下查询可以为我们提供预期的输出:
db.collection.aggregate([
{
$sort:{
"timestamp":1
}
},
{
$group:{
"_id":"$id",
"counts":{
$push:"$count"
}
}
},
{
$project:{
"differences":{
$reduce:{
"input":"$counts",
"initialValue":{
"values":[],
"lastValue":0
},
"in":{
"values":{
$concatArrays:[
"$$value.values",
[
{
$subtract:["$$this","$$value.lastValue"]
}
]
]
},
"lastValue":"$$this"
}
}
}
}
},
{
$project:{
"_id":0,
"id":"$_id",
"plots":"$differences.values"
}
}
]).pretty()
数据集:
{
"_id" : ObjectId("5d724550ef5e6630fde5b71e"),
"id" : "someName",
"timestamp" : "2019-09-05T06:24:24.689+00:00",
"count" : 50
}
{
"_id" : ObjectId("5d724550ef5e6630fde5b71f"),
"id" : "someName",
"timestamp" : "2019-09-04T06:24:24.689+00:00",
"count" : 40
}
{
"_id" : ObjectId("5d724796ef5e6630fde5b720"),
"id" : "someName",
"timestamp" : "2019-09-06T06:24:24.689+00:00",
"count" : 61
}
{
"_id" : ObjectId("5d724796ef5e6630fde5b721"),
"id" : "someName",
"timestamp" : "2019-09-07T06:24:24.689+00:00",
"count" : 72
}
{
"_id" : ObjectId("5d724796ef5e6630fde5b722"),
"id" : "someName",
"timestamp" : "2019-09-08T06:24:24.689+00:00",
"count" : 93
}
{
"_id" : ObjectId("5d724796ef5e6630fde5b723"),
"id" : "someName",
"timestamp" : "2019-09-09T06:24:24.689+00:00",
"count" : 100
}
输出:
{ "id" : "someName", "plots" : [ 40, 10, 11, 11, 21, 7 ] }
解释:我们将count
相同的推id
入counts
数组,然后对其应用$reduce操作以准备一组新值,其中当前值将保持counts
数组的当前值和先前值之间的差异。对于第一个值,前一个值被视为零。
推荐阅读
- jenkins - Jenkins Pull Request Builder 插件中不可用的凭据
- kubernetes - 列出/获取对象时从 Kubernetes 重现错误
- statistics - 如何查看我的调查回复是否具有统计意义?
- javascript - “ForEach 不是函数”无法使 console.log 选择过滤器
- r - 运行与被调用不同的函数(map.poly) - R
- machine-learning - 有人可以解释使用 RNN 的回归模型的批量大小和时间步长吗?
- sql-server - 插入堆时的 SQL Server 缓冲区锁存器争用
- python - 类“int”没有定义“__getitem__”,因此不能在其实例上使用“[]”运算符
- javascript - Appscript-等待gsheets完全加载然后复制行和列?
- python - 使用 Selenium web scraper 响应 403 - 如何修复?