Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mongoDB - average on array values

Tags:

mongodb

nosql

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?

like image 512
Doc_1faux Avatar asked Apr 20 '26 23:04

Doc_1faux


1 Answers

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"}
 }}
]);
like image 116
numbers1311407 Avatar answered Apr 23 '26 17:04

numbers1311407