问题描述
我想知道在 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 以检测时间序列中的值变化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!