$geoNear aggregation ignoring maxDistance

旧巷老猫 提交于 2019-12-23 05:00:09

问题


The following query should return cities within a distance of lng and lat. The city collection has an 2dsphere index on its gps field.

City.native(function(err, collection) {
    collection.aggregate([{
        $geoNear: {
            near: {
                type: 'Point',
                coordinates: [lng, lat]
            },
            distanceField: 'dist',
            limit: limit,
            maxDistance: distance,
            distanceMultiplier: 1,
            spherical: true
        }
    }], function(err, result) {
            return res.send(result);
        }
    });
});

My problem is that when I set distance to 0 the query still returns documents with e.g.

"dist": 27507.15237596358

But it shouldn't return anything because there is no city within a distance of 0. Any ideas what I am doing wrong?


Query:

lat=51.9637151&lng=8.5610982&distance=1

returns a document with following position:

"gps": {
  "type": "Point",
  "coordinates": [
    8.906756,
    52.030319
  ]
},
"dist": 24824.18378549408

But maxDistance is set to 1.


Before I used aggregation in the code above I used this code and it worked:

City.native(function(err, collection) {
    collection.geoNear(lng, lat, {
        limit: limit,
        maxDistance: maxDistance / 6371, // in km
        distanceMultiplier: 6371, // converts radians to miles (use 6371 for km)
        spherical: true
}, function(err, result) {});

However when I changed to aggregation it stopped working.


回答1:


I solved it with following query:

$geoNear: {
   near: {
      type: 'Point',
      coordinates: [lng, lat]
   },
   distanceField: 'dist',
   limit: limit,
   maxDistance: distance * 1000,
   distanceMultiplier: 1 / 1000,
   spherical: true
}

It seems that maxDistance accepts values as meters. So if I want it to accept KM I need to multiply it by 1000. To output distance as KM the distanceMultiplier has to be 1/1000.



来源:https://stackoverflow.com/questions/25862801/geonear-aggregation-ignoring-maxdistance

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