mongoDB-数组值的平均值

mongoDB-数组值的平均值,mongodb,nosql,Mongodb,Nosql,我试图为集合中的每个文档计算数组中每个值的平均聚合操作 Document structure { myVar: myValue, [...] myCoordinates: [ myLng, myLat ] } 因此,我试图通过如下方式查询整个文档集合来计算myLng的平均值和myLat的myCoordinates数组值: myColl.aggregate([{ $group: { _id: 0, lngAvg:

我试图为集合中的每个文档计算数组中每个值的平均聚合操作

Document structure

{
   myVar: myValue,
   [...]
   myCoordinates: [
      myLng,
      myLat
   ]
}
因此,我试图通过如下方式查询整个文档集合来计算myLng的平均值和myLatmyCoordinates数组值:

myColl.aggregate([{
   $group: {
       _id: 0,
       lngAvg: { $avg: "$myCoordinates.0" },
       latAvg: { $avg: "$myCoordinates.1" }
   }
}])
但不幸的是,它不起作用,并为lngAvglatAvg字段返回0值


你有什么想法吗?这至少可行吗?

聚合中的位置表示法似乎仍然不受支持

正如@Sammaye所说的,您需要首先解开数组,或者用嵌入的
lng
/
lat
嵌入文档替换坐标数组,这将使这个过程变得微不足道

考虑到阵列结构,您可以像这样展开和投影lat/lng:

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"}
 }}
]);

我想你需要先$unwind文档谢谢你的帮助,我可以用你的查询来调整我的查询,它会工作的!:)不幸的是,我不能为
lng
/
lat
夫妇使用文档,因为我在文档上使用了二维地理索引。我担心在数组上使用“展开”操作符会丢失对根文档的任何引用,但它似乎会通过用每个值替换数组来为数组中包含的每个值返回根文档的副本。我希望他们很快会在聚合中修复位置符号,以简化二维地理索引的聚合操作。地理空间索引应该已经可以在
lng
/
lat
嵌入式文档上使用了。