Search code examples
mongodbmongodb-geospatial

Does MongoDB provide the distance to point with $nearSphere operator?


The $nearSphere MongoDB operator is able to return the documents near to a given point (specified as parameter of the operator) sorted by incresing distance.

However, how to get the actual distance? Is there any mean of getting this using MongoDB functionality? Either with $nearSphere (although I have checked its documentation and I haven't found this information) or with other mechanisms (maybe the aggregation framework?)

Thanks!


Solution

  • With aggregation you can use the $geoNear stage to provide both spherical geometry and return the distance.

    Example from the docs:

    db.places.aggregate([
       {
         $geoNear: {
            near: { type: "Point", coordinates: [ -73.99279 , 40.719296 ] },
            distanceField: "dist.calculated",
            maxDistance: 2,
            query: { category: "Parks" },
            includeLocs: "dist.location",
            spherical: true
         }
       }
    ])