如何在对象内部排序并减去MongoDB中对象内部的值
Posted
技术标签:
【中文标题】如何在对象内部排序并减去MongoDB中对象内部的值【英文标题】:how to sort inside the object and subtract the values inside the objects in MongoDB 【发布时间】:2021-10-24 09:52:37 【问题描述】:输入文件
"data":
"2021-05-05":
"12": 2.1,
"15": 0.2,
"06": 2.6,
"09": 2.2
,
"2021-05-06":
"12": 2.1,
"15": 0.2,
"06": 2,
"09": 1.7
中间步骤数据objects
将与键连接并按时间排序。
"data":
"2021-05-05":
"2021-05-05T06:00:00:0Z": 2.6,
"2021-05-05T09:00:00:0Z": 2.2,
"2021-05-05T12:00:00:0Z": 2.1,
"2021-05-05T15:00:00:0Z": 0.2
,
"2021-05-06":
"2021-05-06T12:00:00:0Z": 2.1,
排序后。下一步将是。 Subtract
从value_last
- value_first
相对于时间。
输出文档
Document 1
"data":
"time_first" : "2021-05-05T06:00:00:0Z",
"value_first": 2.6,
"time_last": "2021-05-05T15:00:00:0Z"
"value_last": "0.2",
"difference_value_last-value_first" : -0.4
Document 2
如果只包含一个值,则上个月的value_last成为下一个文档的value_first
。
"data":
"time_first" : "2021-05-05T15:00:00:0Z",
"value_first": 0.2,
"time_last": "2021-05-06T12:00:00:0Z",
"value_last": : 2.1 ,
"difference_value_last-value_first" : 1.9
【问题讨论】:
【参考方案1】:你可以使用聚合
$objectToArray
把对象变成一个数组,所以我们可以得到键:值对,它定义了名称“k”,有助于获取数据
$unwind
解构数组
$sort
按条件排序
$group
查找我们排序的第一个和最后一个元素
$concat
拼接字符串日期时间字符串
这里是代码
db.collection.aggregate([
$project: data: "$objectToArray": "$data ,
$project:
data:
$map:
input: "$data",
in:
"dk": "$$this.k",
"dv": "$objectToArray": "$$this.v"
,
"$unwind": "$data" ,
$unwind: "$data.dv" ,
$sort:
"data.dk": -1,
"data.dv.v": -1
,
$group:
_id: "$data.dk",
firstData: $first: "$data.dv" ,
lastData: $last: "$data.dv"
,
$project:
"time_first":
$concat: [ "$_id", "T", "$firstData.k", ":00:00:0Z" ]
,
"time_last":
$concat: [ "$_id", "T", "$lastData.k", ":00:00:0Z" ]
,
"value_first": "$firstData.v",
"value_last": "$lastData.v",
"difference_value_last-value_first":
"$subtract": [ "$lastData.v", "$firstData.v" ]
])
工作Mongo playground
【讨论】:
以上是关于如何在对象内部排序并减去MongoDB中对象内部的值的主要内容,如果未能解决你的问题,请参考以下文章
带有 elemMatch 的 MongoDB 查询,用于从对象内部匹配嵌套数组数据 [重复]
如何避免在对象内部创建对象并使用猫鼬将元素直接推送到快速数组中?