mongoDB - average on array values

六月ゝ 毕业季﹏ 提交于 2020-12-10 08:00:59

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!