This chapter introduces one of MongoDB's geospatial query functions, which is to query document data based on distance.

Application scenarios: searching for nearby stores, and finding nearby people.

Prerequisite Tutorial

MongoDB Geospatial Data Storage Format

The prerequisites for querying data based on distance are as follows:

  • Each document data contains a field that stores coordinate data, for example: the location field stores the coordinates of a store.
  • Create a 2dsphere or 2d spatial index.

The $near Operator

MongoDB uses the $near operator to query document data based on distance.

Format:

{
   <location field>: { // Field that stores the coordinate data
     $near: {
       $geometry: { // Set the reference coordinates for comparison
          type: "Point" ,
          coordinates: [ longitude , latitude ]
       },
       $maxDistance: maximum distance, in meters,
       $minDistance: minimum distance, in meters
     }
   }
}

Note: The data returned by the $near query is sorted from nearest to farthest.

Example

Suppose the shop collection stores store data, where the location field stores the coordinates of each store. The following query finds the nearest store to me (minimum distance 1000 meters, maximum distance 5000 meters).

db.shop.find(
   {
     location:
       { $near :
          {
            $geometry: { type: "Point",  coordinates: [ -73.9667, 40.78 ] }, // My coordinates
            $minDistance: 1000, // Minimum distance
            $maxDistance: 5000 // Maximum distance
          }
       }
   }
)