Changed in version 2.4.
The $near operator specifies a point for which a geospatial query returns the 100 closest documents. 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. For GeoJSON points, use a 2dsphere index. For legacy coordinate pairs, use a 2d index.
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 100 documents with coordinates nearest to [ 40 , 5 ] and limits the maximum distance to 100 meters from the specified GeoJSON point:
db.places.find( { loc : { $near :
{ $geometry :
{ type : "Point" ,
coordinates: [ 40 , 5 ] } },
$maxDistance : 100
} } )
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 selects the 100 documents with coordinates nearest to [ 40 , 5 ]:
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.