MongoDB print distance between two points

You can use the $geoNear aggregate pipeline stage to produce a distance from the queried point:

 db.new_stores.aggregate([
    { "$geoNear": {
        "near": {
            "type": "Point",
            "coordinates": [ -81.093699, 32.074673 ]
        }, 
        "maxDistance": 500 * 1609,
        "key" : "myLocation",
        "spherical": true,
        "distanceField": "distance",
        "distanceMultiplier": 0.000621371
    }}
]).pretty()

This allows you to specify "distanceField" which will produce another field in the output documents containing the distance from the queried point. You can also use "distanceMultiplier" to apply any conversion to the output distance as required ( i.e meters to miles, and noting that all GeoJSON distances are returned in meters )

There is also the geoNear command with similar options, but it of course does not return a cursor as output.

if you have more than one 2dsphere, you should specify a "key".

Leave a Comment