问题
I'm trying to compute an average aggregation operation on each values of an array for each documents in my collection.
Document structure
{
myVar: myValue,
[...]
myCoordinates: [
myLng,
myLat
]
}
So, I tried to compute average of myLng and myLat values of myCoordinates array for the whole collection of documents by querying the collection like this :
myColl.aggregate([{
$group: {
_id: 0,
lngAvg: { $avg: "$myCoordinates.0" },
latAvg: { $avg: "$myCoordinates.1" }
}
}])
But unfortunately, it doesn't work and returns me a value of 0 for both lngAvg and latAvg fields.
Have you some ideas? Is this feasible at least?
回答1:
Positional notation in aggregation seems to still be unsupported, check out this ticket.
As @Sammaye says you'd need to either unwind the array first, or replace your coordinates array with an embedded lng
/lat
embedded doc, which would make this trivial.
Given the array structure, you might unwind and project the lat/lng like this:
myColl.aggregate([
// unwind the coordinates into separate docs
{$unwind: "$myCoordinates"},
// group back into single docs, projecting the first and last
// coordinates as lng and lat, respectively
{$group: {
_id: "$_id",
lng: {$first: "$myCoordinates"},
lat: {$last: "$myCoordinates"}
}},
// then group as normal for the averaging
{$group: {
_id: 0,
lngAvg: {$avg: "$lng"},
latAvg: {$avg: "$lat"}
}}
]);
来源:https://stackoverflow.com/questions/17302495/mongodb-average-on-array-values