在我的申请表中,我有以下文件
{
"timestamp": ISODate("2015-09-17T21:14:35.0Z"),
"sensor": "gas-in",
"value": 2.5,
},
{
"timestamp": ISODate("2015-09-17T21:14:35.0Z"),
"sensor": "gas-out",
"value": 2.0,
},
{
"timestamp": ISODate("2015-09-17T21:20:35.0Z"),
"sensor": "gas-in",
"value": 6.3,
},
{
"timestamp": ISODate("2015-09-17T21:20:35.0Z"),
"sensor": "gas-out",
"value": 0.8,
}
...等...
如何返回差异(气体输入) - (气体输出)按时间戳分组? 我正在尝试编写一个返回它的函数:
{
"timestamp": ISODate("2015-09-17T21:14:35.0Z"),
"sensor": "gas-difference",
"value": 0.5, // is calculated by 2.5 - 2.0
},
{
"timestamp": ISODate("2015-09-17T21:20:35.0Z"),
"sensor": "gas-difference",
"value": 5.5, // is calculated by 6.3 - 0.8
},
...等...
我玩过聚合函数和$减法,阅读其他SO问题,但他们似乎没有我的问题的答案。在其他问题中,他们似乎知道哪两个文档相互减去,但在我的情况下,我不知道文档的数量,$ timestamp“column”是两个文档的匹配标识符。
有人可以帮我解决这个问题吗?谢谢!
答案 0 :(得分:4)
您首先需要的是基于每个值的分组中$sum
运算符的条件$cond
。然后您可以单独$subtract
:
db.gas.aggregate([
{ "$group": {
"_id": "$timestamp",
"gas-in": {
"$sum": {
"$cond": [
{ "$eq": [ "$sensor", "gas-in" ] },
"$value",
0
]
}
},
"gas-out": {
"$sum": {
"$cond": [
{ "$eq": [ "$sensor", "gas-out"] },
"$value",
0
]
}
},
}},
{ "$project": {
"gasdifference": { "$subtract": [ "$gas-in", "$gas-out" ] }
}}
])
结果如下:
{ "_id" : ISODate("2015-09-17T21:20:35Z"), "gasdifference" : 5.5 }
{ "_id" : ISODate("2015-09-17T21:14:35Z"), "gasdifference" : 0.5 }
替代方案只是让#34;气喘"单个阶段的值为负值:
db.gas.aggregate([
{ "$group": {
"_id": "$timestamp",
"gasdifference": {
"$sum": {
"$cond": [
{ "$eq": [ "$sensor", "gas-in" ] },
"$value",
{ "$subtract": [ 0, "$value" ] }
]
}
}
}}
])
这样会更有效率。
如果你有两个以上的传感器"那么你只需要'#34; nest" $cond
陈述:
db.gas.aggregate([
{ "$group": {
"_id": "$timestamp",
"gasdifference": {
"$sum": {
"$cond": [
{ "$eq": [ "$sensor", "gas-in" ] },
"$value",
{ "$cond": [
{ "$eq": [ "$sensor", "gas-out" ] },
{ "$subtract": [ 0, "$value" ] },
0
]}
]
}
}
}}
])
因为他们是"三元"运算符(if-then-else)然后任何进一步的逻辑都在" else"条件。