Anda dapat mencoba agregasi di bawah ini dalam pipa 3.4.
Tetapkan bobot berdasarkan posisi elemen.
$switch
case untuk memberikan bobot yang berbeda berdasarkan ukuran array.
db.col.aggregate([{"$addFields":{
"myArray":{
"$switch":{
"branches":[{
"case":{"$gt":[{"$size":"$myArray"},2]},
"then":{"$concatArrays":[
[{"value":{"$arrayElemAt":["$myArray.value",0]},"weight":{"$divide":[2,5]}}],
{"$map":{
"input":{"$slice":["$myArray",1,{"$subtract":[{"$size":"$myArray"},2]}]},
"as":"val",
"in":{"value":"$$val.value","weight":{"$divide": [{"$divide":[1,5]},{"$subtract":[{"$size":"$myArray"},2]} ]}}
}},
[{"value":{"$arrayElemAt":["$myArray.value",-1]},"weight":{"$divide":[2,5]}}]
]}
},
{
"case":{"$eq":[{"$size":"$myArray"},2]},
"then":{"$concatArrays":[
[{"value":{"$arrayElemAt":["$myArray.value",0]},"weight":{"$divide":[1,2]}}],
[{"value":{"$arrayElemAt":["$myArray.value",-1]},"weight":{"$divide":[1,2]}}]
]}
}],
"default":{"$concatArrays":[
[{"value":{"$arrayElemAt":["$myArray.value",0]},"weight":1}],
]}}
}
}},
{"$unwind":"$myArray"},
{"$group":{
"_id":"$myArray.value",
"linear_total":{"$sum":{"$multiply":["$myArray.weight","$total"]}}
}},
{"$sort":{"_id":1}}])