Search MongoDB by closest region based on coordinates

Viewed 18

I'm using MongoDB to store about 1 million documents representing regions.

Each document contains a coordinates record in the following format

"coordinates" : {
    "longitude" : -77.02687,
    "latitude" : 38.888565
}

Given a set of coordinates { x, y }, what query should I run to find the region ( document ) that is closest to it?

1 Answers

Based on the MongoDB geospatial-queries documentation the answer is quite simple.

In order to query for locations near a region you should follow these steps

Step 1

Create an index on the location field

db.places.createIndex( { location: "2dsphere" } )

Step 2

Find regions close to { -73.9667, 40.78 } ordered by closest locations

db.places.aggregate( [
   {
      $geoNear: {
         near: { type: "Point", coordinates: [ -73.9667, 40.78 ] },
         spherical: true,
         query: { category: "Parks" },
         distanceField: "calcDistance"
      }
   }
] )
Related