按$ geonear汇总

我有一个看起来像这样的集合:

[ { "roadname": "foo", "data": [ { "val": 50, "loc": { "type": "Point", "coordinates": [3.197033554, 50.64611712] } } }, { "val": NULL, "loc": { "type": "Point", "coordinates": [3.197740735, 50.6460058] } } } ] }, { "roadname": "foo", "data": [ { "val": 50, "loc": { "type": "Point", "coordinates": [3.32456512, 50.2744516] } } } ] }, { "roadname": "bar", "data": [ { "val": 145, "loc": { "type": "Point", "coordinates": [3.198408689, 50.64586985] } } } ] } ] 

我在地图上显示每个data.loc ,然后将其引导至: 派出点 。 (点颜色代表val字段)

编辑3:为了澄清我的数据库结构,这里是一个确切的数据库表示。 每条灰线代表来自提供的数据集的根元素: 线条点

我想“ 分组点近(使用data.loc ),并有相同的父母name ”,并汇总他们的val (说平均来说简单),以便显示这样的东西: 聚合点

编辑3:重要的是要明白,我试图聚合的观点不共享任何共同的财产或祖先。 他们唯一常见的分区是他们的空间接近度

我知道neargeoneargroup ,但我只是无法find解决scheme来做到这一点。

我想要使​​用一个纯粹的mongodb解决scheme。 如果这是不可能的,我可以使用turf.js或其他库,但我只是努力find一个可行的和可扩展的方式来做到这一点。


编辑:集合上的主要元素代表一条道路,所以道路上的所有点都具有相同的父roadname


编辑2:数据可以在这里find

我认为这将会为你工作。 我把你的数据集aggregationspointsdata.json导入一个名为roads的mongo集合。

这是Mongo中的一个簇。 所以,每个文档都代表一个集群,或者从您提供的数据集中获得数组中的一个元素。 需要记住的一件事是,只有当应该组合在一起的点集群有一些标识符时,这才会起作用。 在我的例子中,它是_id

 > db.roads.findOne() { "_id" : ObjectId("583ee50bd7c4d711d45c7757"), "roadname" : "RD700", "data" : [ { "val" : null, "loc" : { "type" : "Point", "coordinates" : [ 3.197033554, 50.64611712 ] } }, { "val" : null, "loc" : { "type" : "Point", "coordinates" : [ 3.197740735, 50.6460058 ] } }, { "val" : 145, "loc" : { "type" : "Point", "coordinates" : [ 3.198408689, 50.64586985 ] } }, ] } 

这是您可以运行的mongo聚合,将返回每个群集的平均值。 我什至使它返回相同的GeoJSON格式。

 db.roads.aggregate([ //unravel the cluster here { $unwind: "$data" }, //project the coordinates to more readable names while preserving roadname and GeoJSON type. { $project: {roadname: 1, type: "$data.loc.type", val : "$data.val", lng: { $arrayElemAt: ["$data.loc.coordinates",0]}, lat: { $arrayElemAt: ["$data.loc.coordinates",-1]}}}, //group on cluster id while preserving type and roadname. Take avergae of value, lat and long. { $group: { _id : "$_id", roadname: {$first:"$roadname"}, type: {$first: "$type"}, avgLng: { $avg: "$lng" },avgLat: { $avg: "$lat" }, avgVal: { $avg : "$val" }}}, //re-project to fit the similar format of original collection { $project: { _id: 1, roadname: 1, data : { val: "$avgVal", loc: {type : "$type", coordinates: ["$avgLng", "$avgLat"]}} }} ]) 

您还可以在聚合pipe道的末端添加额外的$out ,将所有这些平均质心移动到另一个更易于pipe理的集合。

这是在上面显示的聚合pipe道调用之后的结果。

 [ { "_id": ObjectId("583ee50bd7c4d711d45c775c"), "roadname": "RD700", "data": { "val": 144.03703703703704, "loc": { "type": "Point", "coordinates": [ 3.2232721289257142, 50.67602178708569 ] } } }, { "_id": ObjectId("583ee50bd7c4d711d45c775b"), "roadname": "RD700", "data": { "val": 170.0344827586207, "loc": { "type": "Point", "coordinates": [ 3.22367598656322, 50.67626952408046 ] } } }, ... ]