查询mongo检测时间序列的值变化

编程入门 行业动态 更新时间:2024-10-25 06:27:11
本文介绍了查询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-01、2018-04-03 和 2018-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检测时间序列的值变化

本文发布于:2023-10-24 19:31:10,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1524807.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:序列   时间   mongo

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!