Вы можете попробовать агрегацию ниже, чтобы получить результат, логика заключается в использовании $reduce
для вычисления промежуточного итога
конвейер агрегации
db.t32.aggregate([
{$group : {_id : "$piece_id", data : {$push : "$$ROOT"}}},
{$addFields : {data :
{$reduce : {
input : "$data",
initialValue : [{previous_value : 0, total_produced : 0, new_value : 0}],
in : {$concatArrays :
[ "$$value",[{$mergeObjects : ["$$this", { previous_value : {$arrayElemAt : ["$$value.new_value", -1]} , total_produced : "$$this.total_produced", new_value : {$sum : ["$$this.total_produced",{$arrayElemAt : ["$$value.new_value", -1]}]}}]}]]
}
}}
}},
{$addFields : {data : {$slice : ["$data", 1, {$size : "$data"}]}}}
]).pretty()
коллекция образцов
> db.t32.find()
{ "_id" : "5bfc2a16b4f11f3760ed4b64", "piece_id" : "12345", "finish_date" : "2018-11-26T17:15:09.795Z", "total_produced" : 500 }
{ "_id" : "5bfc2a16b4f11f3760ed4b65", "piece_id" : "12345", "finish_date" : "2018-11-27T17:15:09.795Z", "total_produced" : 750 }
{ "_id" : "5bfc2a16b4f11f3760ed4b66", "piece_id" : "12345", "finish_date" : "2018-11-28T17:15:09.795Z", "total_produced" : 250 }
результат агрегирования
> db.t32.aggregate([
... {$group : {_id : "$piece_id", data : {$push : "$$ROOT"}}},
... {$addFields : {data :
... {$reduce : {
... input : "$data",
... initialValue : [{previous_value : 0, total_produced : 0, new_value : 0}],
... in : {$concatArrays :
... [ "$$value",[{$mergeObjects : ["$$this", { previous_value : {$arrayElemAt : ["$$value.new_value", -1]} , total_produced : "$$this.total_produced", new_value : {$sum : ["$$this.total_produced",{$arrayElemAt : ["$$value.new_value", -1]}]}}]}]]
... }
... }}
... }},
... {$addFields : {data : {$slice : ["$data", 1,1000]}}}
... ]).pretty()
{
"_id" : "12345",
"data" : [
{
"_id" : "5bfc2a16b4f11f3760ed4b64",
"piece_id" : "12345",
"finish_date" : "2018-11-26T17:15:09.795Z",
"total_produced" : 500,
"previous_value" : 0,
"new_value" : 500
},
{
"_id" : "5bfc2a16b4f11f3760ed4b65",
"piece_id" : "12345",
"finish_date" : "2018-11-27T17:15:09.795Z",
"total_produced" : 750,
"previous_value" : 500,
"new_value" : 1250
},
{
"_id" : "5bfc2a16b4f11f3760ed4b66",
"piece_id" : "12345",
"finish_date" : "2018-11-28T17:15:09.795Z",
"total_produced" : 250,
"previous_value" : 1250,
"new_value" : 1500
}
]
}
>