Mongodb aggregation query to subtract and grouping of cumulative value

后端 未结 1 501
野的像风
野的像风 2020-12-16 21:49
{
\"_id\" : ObjectId(\"58f5a22d22679039176d2ee8\"),
\"MachineID\" : NumberInt(\"1001\"),
\"Timestamp\" : ISODate(\"2017-04-18T07:01:01.000+05:30\"), 
\"Utilization\"         


        
相关标签:
1条回答
  • 2020-12-16 22:11

    How's this? It doesn't compute the hour, but it does everything else.

    [
        {
          $match: {
              $and: [
                  {MachineID: {$in: [1001]}},
                  {
                    Timestamp: {
                        $gte: ISODate("2017-04-18T01:30:00.000Z"),
                        $lte: ISODate("2017-04-19T01:30:00.000Z")
                    }
                  }
              ]
          }
        },
        // Add all data to one array.
        {$group: {_id: "$MachineID", all: {$push: "$$ROOT"}}},
        // Create an array of (element, array index) pairs.
        {$addFields: {allWithIndex: {$zip: {inputs: ["$all", {$range: [0, {$size: "$all"}]}]}}}},
        // Create an array of {current: <element>, previous: <previous element>} pairs.
        {
          $project: {
              pairs: {
                  $map: {
                      input: "$allWithIndex",
                      in : {
                          current: {$arrayElemAt: ["$$this", 0]},
                          prev: {
                              $arrayElemAt: [
                                  "$all",
                                  // Set prev == current for the first element.
                                  {$max: [0, {$subtract: [{$arrayElemAt: ["$$this", 1]}, 1]}]}
                              ]
                          }
                      }
                  }
              }
          }
        },
        // Compute the deltas.
        {$unwind: "$pairs"},
        {
          $group: {
              _id: {MachineID: "$_id", RunStatus: "$pairs.current.RunStatus"},
              ProductsCount:
                  {$sum: {$subtract: ["$pairs.current.ProductsCount", "$pairs.prev.ProductsCount"]}},
              Utilization:
                  {$sum: {$subtract: ["$pairs.current.Utilization", "$pairs.prev.Utilization"]}},
          }
        }
    ]
    
    0 讨论(0)
提交回复
热议问题