You can use Aggregation Framework and $avg.
$avg can be used in $project or $group.
https://docs.mongodb.com/manual/reference/operator/aggregation/avg/
With a single expression as its operand, if the expression resolves to
an array, $avg traverses into the array to operate on the numerical
elements of the array to return a single value. With a list of
expressions as its operand, if any of the expressions resolves to an
array, $avg does not traverse into the array but instead treats the
array as a non-numerical value.
UPDATE #2:
since the problem is now more clear, i will update my answer.
db.stackoverflow027.aggregate([
{
$match: {
"message.testnr":"1111"
}
},
{
$unwind: {
path: "$message.content.deflection",
includeArrayIndex: "position"
}
},
{
$group: {
_id: "$position",
averageForIndex: {$avg: "$message.content.deflection"}/*,
debug_totalIndexInvolvedInTheAverage: {$sum: 1},
debug_valueInvolvedInTheAverage: {$push: "$message.content.deflection"},
debug_documentInvolvedInTheAverage: {$push: "$$ROOT"}*/
}
},
{
$sort: {_id:1}
},
{
$group: {
_id: null,
average: {$push: "$averageForIndex"}
}
}
], { allowDiskUse: true });
That will give you this output:
{
"_id" : null,
"average" : [
6.0,
7.0,
8.0,
9.0,
10.0
]
}
I also added { allowDiskUse: true } in order to avoid memory limitations (check the link to have more informations).
Hope now your problem is solved.
You can see some "debug_" property in order to give you the opportunity to figure out what really happen at $group iteration. But you can remove this property in product environmental.