MongoDB print distance between two points

MongoDB provides a $geoNear aggregator for calculating the distance of documents in a collection with GeoJson coordinates.

Let us understand it with a simple example. Consider a simple collection shops

1. Create Collection

db.createCollection('shops')

2. Insert documents in shops collections

db.shops.insert({name:"Galaxy store",address:{type:"Point",coordinates:[28.442894,77.341299]}})

db.shops.insert({name:"A2Z store",address:{type:"Point",coordinates:[28.412894,77.311299]}})

db.shops.insert({name:"Mica store",address:{type:"Point",coordinates:[28.422894,77.342299]}})

db.shops.insert({name:"Full Stack developer",address:{type:"Point",coordinates:[28.433894,77.334299]}})

3. create GeoIndex on "address" fields

db.shops.createIndex({address: "2dsphere" } )

4. Now use a $geoNear aggregator to find out the documents with distance.

db.shops.aggregate([{$geoNear:{near:{type:"Point",coordinates:[28.411134,77.331801]},distanceField: "shopDistance",$maxDistance:150000,spherical: true}}]).pretty()

Here coordinates:[28.411134,77.331801] is the center position or quired position from where documents will be fetched.

distanceField:"shopDistance" , $geoNear Aggregator return shopDistance as fields in result.

Result:

{ "_id" : ObjectId("5ef047a4715e6ae00d0893ca"), "name" : "Full Stack developer", "address" : { "type" : "Point", "coordinates" : [ 28.433894, 77.334299 ] }, "shopDistance" : 621.2848190449148 }
{ "_id" : ObjectId("5ef0479e715e6ae00d0893c9"), "name" : "Mica store", "address" : { "type" : "Point", "coordinates" : [ 28.422894, 77.342299 ] }, "shopDistance" : 1203.3456146763526 }
{ "_id" : ObjectId("5ef0478a715e6ae00d0893c7"), "name" : "Galaxy store", "address" : { "type" : "Point", "coordinates" : [ 28.442894, 77.341299 ] }, "shopDistance" : 1310.9612119555288 }
{ "_id" : ObjectId("5ef04792715e6ae00d0893c8"), "name" : "A2Z store", "address" : { "type" : "Point", "coordinates" : [ 28.412894, 77.311299 ] }, "shopDistance" : 2282.6640175038788 }

Here shopDistance will be in meter.


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,
        "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.