Как е това? Не изчислява часа, но прави всичко останало.
[
{
$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"]}},
}
}
]