MongoDB print distance between two points

When I run this query on MongoDB, I get all the places in the immediate vicinity of 500 miles to the specified coordinates. But I want to know the exact distance between the specified coordinates and the location of the result.

db.new_stores.find({ "geometry": { $nearSphere: { $geometry: { type: "Point", coordinates: [ -81.093699, 32.074673 ] }, $maxDistance: 500 * 3963 } } } ).pretty() 

My output looks like this:

 { "_id" : ObjectId("565172058bc200b0db0f75b1"), "type" : "Feature", "geometry" : { "type" : "Point", "coordinates" : [ -80.148826, 25.941116 ] }, "properties" : { "Name" : "Anthony Coal Fired Pizza", "Address" : "17901 Biscayne Blvd, Aventura, FL" } } 

I also want to know the distance of this place from the specified coordinate. I created a 2dsphere index on geometry.

+5
source share
1 answer

You can use the $geoNear aggregation $geoNear to create a distance from the requested 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 a "distanceField" that will call another field in the output documents containing the distance from the requested point. You can also use "distanceMultiplier" to apply any conversion to the output distance as needed (from meter to miles and noting that all GeoJSON distances are returned in meters).

There is also the geoNear command with similar parameters, but it certainly does not return the cursor as output.

+9
source

Source: https://habr.com/ru/post/1236584/


All Articles