On this page本页内容
$near
¶Specifies a point for which a geospatial query returns the documents from nearest to farthest. The $near
operator can specify either a GeoJSON point or legacy coordinate point.
$near
requires a geospatial index:
To specify a GeoJSON point, $near
operator requires a 2dsphere index and has the following syntax:语法如下所示:
If specifying latitude and longitude coordinates, list the longitude first and then latitude:
-180
and 180
, both inclusive.-90
and 90
, both inclusive.When specifying a GeoJSON point, you can use the optional
$minDistance
and $maxDistance
specifications to limit the $near
results by distance in meters:
$minDistance
limits the results to those documents that are at least the specified distance from the center point.$maxDistance
limits the results to those documents that are at most the specified distance from the center point.To specify a point using legacy coordinates, $near
requires a 2d index and has the following syntax:语法如下所示:
When specifying a legacy coordinate, you can use the optional
$maxDistance
specification to limit the $near
results by distance in radians. $maxDistance
limits the results to those documents that are at most the specified distance from the center point.
You cannot combine the $near
operator, which requires a special geospatial index, with a query operator or command that requires another special index. For example you cannot combine $near
with the $text
query.
Starting in MongoDB 4.0, $near
queries are supported for sharded collections.
In earlier MongoDB versions, $near
queries are not supported for sharded collections; instead, for sharded clusters, you must use the $geoNear
aggregation stage or the geoNear
command (available in MongoDB 4.0 and earlier).
$near
sorts documents by distance. If you also include a sort()
for the query, sort()
re-orders the matching documents, effectively overriding the sort operation already performed by $near
. When using sort()
with geospatial queries, consider using $geoWithin
operator, which does not sort documents, instead of $near
.
See also参阅
Important
If specifying latitude and longitude coordinates, list the longitude first and then latitude:
-180
and 180
, both inclusive.-90
and 90
, both inclusive.Consider a collection places
that has a 2dsphere
index.
The following example returns documents that are at least 1000
meters from and at most 5000
meters from the specified GeoJSON point, sorted from nearest to farthest:
Important
If specifying latitude and longitude coordinates, list the longitude first and then latitude:
-180
and 180
, both inclusive.-90
and 90
, both inclusive.Consider a collection legacy2d
that has a 2d
index.
The following example returns documents that are at most 0.10
radians from the specified legacy coordinate pair, sorted from nearest to farthest: