On this page本页内容
$nearSphere
¶Specifies a point for which a geospatial query returns the documents from nearest to farthest. MongoDB calculates distances for $nearSphere
using spherical geometry.
$nearSphere
requires a geospatial index:
coordinates
field of the GeoJSON object.The $nearSphere
operator can specify either a GeoJSON point or legacy coordinate point.
To specify a GeoJSON Point, use the following syntax:
$minDistance
limits the results to those documents that are at least the specified distance from the center point.$maxDistance
is available for either index.To specify a point using legacy coordinates, use the following syntax:
$minDistance
is available only if the query uses the 2dsphere index. $minDistance
limits the results to those documents that are at least the specified distance from the center point.$maxDistance
is available for either index.If you use longitude and latitude for legacy coordinates, specify the longitude first, then latitude.
See also参阅
You cannot combine the $nearSphere
operator, which requires a special geospatial index, with a query operator or command that requires another special index. For example you cannot combine $nearSphere
with the $text
query.
Starting in MongoDB 4.0, $nearSphere
queries are supported for sharded collections.
In earlier MongoDB versions, $nearSphere
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).
$nearSphere
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 $nearSphere
. When using sort()
with geospatial queries, consider using $geoWithin
operator, which does not sort documents, instead of $nearSphere
.
Consider a collection places
that contains documents with a location
field and has a 2dsphere index.
Then, the following example returns whose location
is at least 1000
meters from and at most 5000
meters from the specified point, ordered from nearest to farthest:
2d
Index¶Consider a collection legacyPlaces
that contains documents with legacy coordinates pairs in the location
field and has a 2d index.
Then, the following example returns those documents whose location
is at most 0.10
radians from the specified point, ordered from nearest to farthest:
2dsphere
Index¶If the collection has a 2dsphere
index instead, you can also specify the optional $minDistance
specification. For example, the following example returns the documents whose location
is at least 0.0004
radians from the specified point, ordered from nearest to farthest: