Search code examples
node.jsmongodbnode-mongodb-native

$geoNear aggregation ignoring maxDistance


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.


Solution

  • 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.