问题描述
我正在尝试为我的集合中的每个文档计算数组的每个值的平均聚合操作.
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
]
}
因此,我尝试通过查询集合来计算整个文档集合的 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" }
}
}])
但不幸的是,它不起作用并为我返回 lngAvg 和 latAvg 字段的 0 值.
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?
推荐答案
聚合中的位置符号似乎仍然不受支持,检查这张票.
Positional notation in aggregation seems to still be unsupported, check out this ticket.
正如@Sammaye 所说,您需要先展开数组,或者用嵌入的 lng
/lat
嵌入文档替换坐标数组,这将使微不足道.
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.
给定数组结构,您可以像这样展开和投影 lat/lng:
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"}
}}
]);
这篇关于mongoDB - 数组值的平均值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!