Geo Json Query - List all records by checking if given geo point lies within the radius of the record's geo point

Viewed 74

I am building an application where a user searches for a service provider based on location.

The following needs to be considered

  • I save the lat, long for all the service providers and the radius of their servicing area say 5kms
  • Users can search for service providers from any location and I grab the lat, long of the users current location from my frontend.

Lets consider I have the following details

Service providers: S1 : {lat: xxxx, long: xxxx, radius: 5km} S2 : {lat: xxxx, long: xxxx, radius: 6km}

and so on..

Now when a user searches from a particular lat, long I need to list all the service providers in a way where the user's lat, long falls inside the service providers radius.

That would be I need to list all the service providers where distance between user's geo point and Provider's geo point is less than the providers radius

How can I achieve this using mongodb geoSpatial queries ?

1 Answers

In order to use the MongoDB Geo queries, you will need to store the coordinates in either legacy coordinate pairs,

{loc:[long, lat], radius: 5}

or as GeoJson objects

{loc:{type:"point",[long, lat]}, radius: 5}

You will also need a 2dsphere index on the loc field

When you search, first use $geoNear, specifying a field name for distanceField and the radius of the Earth in distanceMultiplier (use the same units as the radius field in the documents). Then use $match to return only documents closer than their corresponding radius.

For example, if the collection contains these documents:

{Name:"Prem Fast Food Corner",
 loc:{type:"Point",
      coordinates:[77.2069656,28.6143675]}, 
 radius:15},
{Name:"The Black Beetle",
 loc:{type:"Point", 
      coordinates:[77.0693677,28.5842962]}, 
 radius:10}

And there is a 2dsphere index on loc, we can query using aggregation to find that Cariappa Parade Ground is within the delivery radius for only one of these restaurants.

db.geo.aggregate([
    {$geoNear:{
               near:[77.1385933,28.6653018],
               distanceField:"distance",
               distanceMultiplier:6378,
               spherical:true
    }},
    {$match:{
         $expr:{
             $lte:[ "$distance", "$radius" ]
         }
    }}
])
Related