查询mongo检测时间序列的值变化 [英] Query mongo to detect value changes in time series

查看:25
本文介绍了查询mongo检测时间序列的值变化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道在 MongoDB 中是否可以进行以下操作.

Im wondering if the following is possible in MongoDB.

我收集了代表某个时间值变化的文档:

I have collection of documents that represent changes in some value in time:

{
  "day" : ISODate("2018-12-31T23:00:00.000Z"),
  "value": [some integer value]
}

数据中没有漏洞",我有一段时间内所有日子的条目.

There are no 'holes' in the data, I have entries for all days within some period.

是否可以查询此集合以仅获取与前一个具有不同值的文档(按天 asc 排序时)?例如,有以下文件:

Is it possible to query this collection to get only documents that has different value than previous one (when sorting by day asc)? For example, having following documents:

{ day: ISODate("2019-04-01T00:00:00.000Z"), value: 10 }
{ day: ISODate("2019-04-02T00:00:00.000Z"), value: 10 }
{ day: ISODate("2019-04-03T00:00:00.000Z"), value: 15 }
{ day: ISODate("2019-04-04T00:00:00.000Z"), value: 15 }
{ day: ISODate("2019-04-05T00:00:00.000Z"), value: 15 }
{ day: ISODate("2019-04-06T00:00:00.000Z"), value: 10 }

我想检索 2018-04-012018-04-032018-04-06 的文档,并且只检索这些文档因为其他人没有价值变化.

I want to retrieve documents for 2018-04-01, 2018-04-03 and 2018-04-06 and only those since others don't have a change of value.

推荐答案

您需要获取成对的连续文档来检测差距.为此,您可以将所有文档推送到单个数组中,然后使用 zip本身从头部移动了 1 个元素:

You need to get pairs of consecutive docs to detect the gap. For that you can push all documents into single array, and zip it with itself shifted 1 element from the head:

db.collection.aggregate([
    { $sort: { day: 1 } },
    { $group: { _id: null, docs: { $push: "$$ROOT" } } },
    { $project: {
        pair: { $zip: {
            inputs:[ { $concatArrays: [ [false], "$docs" ] }, "$docs" ]            
        } }
    } },
    { $unwind: "$pair" },
    { $project: {
        prev: { $arrayElemAt: [ "$pair", 0 ] },
        next: { $arrayElemAt: [ "$pair", 1 ] }
    } },
    { $match: {
         $expr: { $ne: ["$prev.value", "$next.value"] } 
    } },
    { $replaceRoot:{ newRoot: "$next" } }
])

剩下的很简单——你将数组展开回文档,比较对,过滤掉相等的,然后 replaceRoot 从剩下的.

The rest is trivial - you unwind the array back to documents, compare the pairs, filter out the equal ones, and replaceRoot from what's left.

这篇关于查询mongo检测时间序列的值变化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆