我想知道在 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检测时间序列的值变化
发布评论