Navigation
This version of the documentation is archived and no longer supported.

$near

$near

Changed in version 2.4.

Specifies a point for which a geospatial query returns the closest documents first. The query sorts the documents from nearest to farthest.

The $near operator can query for a GeoJSON point or for a point defined by legacy coordinate pairs.

The optional $maxDistance operator limits a $near query to return only those documents that fall within a maximum distance of a point. If you query for a GeoJSON point, specify $maxDistance in meters. If you query for legacy coordinate pairs, specify $maxDistance in radians.

The $near operator requires a geospatial index: a 2dsphere index for GeoJSON points; a 2d index for legacy coordinate pairs. By default, queries that use a 2d index return a limit of 100 documents; however you may use limit() to change the number of results.

Note

You cannot combine the $near operator, which requires a special geospatial index, with a query operator or command that uses a different type of special index. For example you cannot combine $near with the text command.

For queries on GeoJSON data, use the following syntax:

db.<collection>.find(
   { <location field> :
       { $near :
          {
            $geometry : {
               type : "Point" ,
               coordinates : [ <longitude> , <latitude> ]
            },
            $maxDistance : <distance in meters>
          }
       }
    }
)

Important

Specify coordinates in this order: “longitude, latitude.”

The following example selects the documents with coordinates nearest to [ 40 , 5 ] and limits the maximum distance to 500 meters from the specified GeoJSON point:

db.places.find(
   {
     loc:
       { $near :
          {
            $geometry : { type : "Point" , coordinates: [ 40 , 5 ] },
            $maxDistance : 500
          }
       }
   }
)

For queries on legacy coordinate pairs, use the following syntax:

db.<collection>.find( { <location field> :
                         { $near : [ <x> , <y> ] ,
                           $maxDistance: <distance>
                    } } )

Important

If you use longitude and latitude, specify longitude first.

The following example query returns documents with location values that are 10 or fewer units from the point [ 40 , 5 ].

For GeoJSON point object, specify the $maxDistance in meters, not radians.

db.places.find( { loc :
                   { $near : [ 40 , 5 ] ,
                     $maxDistance : 10
                } } )

Note

You can further limit the number of results using cursor.limit().

Specifying a batch size (i.e. batchSize()) in conjunction with queries that use the $near is not defined. See SERVER-5236 for more information.