问题描述
我想知道在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.
是否可以查询此集合以仅获取具有与前一个值不同的文档(按日期升序排序时)?例如,具有以下文档:
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.
我再次发布此问题,因为前一个被错误地标记为重复.
Im posting this question again because previous one was wrongly marked as duplicate.
推荐答案
您需要获取成对的连续文档才能检测出差距.为此,您可以将所有文档放入单个数组,然后 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以检测时间序列中的值变化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!