$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
$nearoperator can query for a GeoJSON point or for a point defined by legacy coordinate pairs.The optional
$maxDistanceoperator limits a$nearquery to return only those documents that fall within a maximum distance of a point. If you query for a GeoJSON point, specify$maxDistancein meters. If you query for legacy coordinate pairs, specify$maxDistancein radians.The
$nearoperator requires a geospatial index: a2dsphereindex for GeoJSON points; a2dindex for legacy coordinate pairs. By default, queries that use a2dindex return a limit of 100 documents; however you may uselimit()to change the number of results.Note
You cannot combine the
$nearoperator, 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$nearwith thetextcommand.For queries on GeoJSON data, use the following syntax:
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:For queries on legacy coordinate pairs, use the following syntax:
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.
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$nearis not defined. See SERVER-5236 for more information.