Array of averages of arrays

Hi,
I have data where each document is of the following format:

{
  id: 0,
  data: [
    {entries: [{value: 1}, {value: 2}]},
    {entries: [{value: 4}, {value: 7}]}
}

I would like to dynamically create a new field (via Charts UI which allows for data aggregation and adding new field) that would represent average of those entries. Eg, for document of id 0 I would like to obtain

avg: [2.5, 4.5]

Where
(1 + 4) / 2 = 2.5,
(2 + 7) / 2 = 4.5.

So essentially zipping those values and averaging them to create new array of averages.

What would be correct aggregation command to achieve that?
Thanks

1 Like

Hi @Tomasz_Borczyk -

Try creating a calculated field with this expression:

{
	$map: {
		input: "$data",
		as: "mappedData",
		in: {
			 $avg: "$$mappedData.entries.value"
		}
	}
}

Or alternatively you can make it an aggregation pipeline in the query bar:

[
	{
		$set: {
			avg: {
				$map: {
					input: "$data",
					as: "mappedData",
					in: {
						 $avg: "$$mappedData.entries.value"
					}
				}
			}
		}
	} 
]

Actually on re-reading your question I realised I’m not calculating the averages the way you want. Your scenario is a little more complex. To (potentially) make things easier: is the number of array elements at either level predictable?

Yes, number of elements in entries is constant, but number of entries in data might differ between documents