Mongodb汇总最大值和最后值的百分比差异

时间:2018-01-06 03:18:31

标签: mongodb

  db['temperatures'].aggregate([
{ $match: {    create_date: { // 200 minutes ago (from now)
    $gt: new Date(ISODate().getTime() - 1000 * 60 * 200)
}}},
{$group: { 
                _id: "Temp",
            temp: {$max: "$temp"},
            last: {$last: "$temp"},
            //how can i get the percentage difference?
        }}
])

如何找到这两个值的百分比差异?

1 个答案:

答案 0 :(得分:2)

希望这会奏效,

db['temperatures'].aggregate([
        { $match: {    create_date: {
            $gt: new Date(ISODate().getTime() - 1000 * 60 * 200)
        }}},
        {$group: { 
                        _id: "Temp",
                    temp: {$max: "$temp"},
                    last: {$last: "$temp"},
        }},
       {$project:{
         _id:'$_id',
         temp:'$temp',
         last:'$last',
         percentage_diff:{$multiply:[{$divide:[{$subtract:["$temp", "$last"]}, "$last"]}, 100]}
        }}
    ])