{
\"_id\" : ObjectId(\"58f5a22d22679039176d2ee8\"),
\"MachineID\" : NumberInt(\"1001\"),
\"Timestamp\" : ISODate(\"2017-04-18T07:01:01.000+05:30\"),
\"Utilization\"
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"]}},
}
}
]