3

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
  • 1
    I think you need to $unwind the document first Commented Jun 25, 2013 at 16:22

1 Answer 1

8

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"}
 }}
]);
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for your help, I could adjust my query with yours and it works! :) Unfortunately, I couldn't use a document for the lng/lat couple since I use a 2d geo index on it. I was worried about loosing any reference to the root document by using the unwind operator on the array but it seems it returns a copy of the root document for each value contained in the array by replacing the array by each value. I hope they'll fix positional notation in aggregation soon to simplify aggregation operations on 2d geo index.
According to the documentation, geospatial indexing should already work on lng/lat embedded docs.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.