$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: a2dsphere
index for GeoJSON points; a2d
index for legacy coordinate pairs. By default, queries that use a2d
index return a limit of 100 documents; however you may uselimit()
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 thetext
command.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$near
is not defined. See SERVER-5236 for more information.