$nearSphere

在本页面

Definition

$nearSphere 需要地理空间索引:

$nearSphere运算符可以指定GeoJSON点或旧坐标点。

要指定GeoJSON Point,请使用以下语法:

{
  $nearSphere: {
     $geometry: {
        type : "Point",
        coordinates : [ <longitude>, <latitude> ]
     },
     $minDistance: <distance in meters>,
     $maxDistance: <distance in meters>
  }
}

2.6 版的新功能。

要使用传统坐标指定点,请使用以下语法:

{
  $nearSphere: [ <x>, <y> ],
  $minDistance: <distance in radians>,
  $maxDistance: <distance in radians>
}

2.6 版的新功能。

如果您将经度和纬度用于旧版坐标,请先指定经度,然后再指定纬度。

Behavior

特殊索引限制

您不能将需要特殊geospatial index$nearSphere运算符与需要另一个特殊索引的查询运算符或命令结合使用。例如,您不能将$nearSphere$text查询结合使用。

分片集合限制

对于分片集合,不支持使用$nearSphere查询。您可以改用geoNear命令或$geoNear聚合阶段。

Sort Operation

$nearSphere按距离对文档进行排序。如果还为查询包括sort(),则sort()重新排序匹配的文档,从而有效地覆盖$nearSphere已经执行的排序操作。将sort()与地理空间查询一起使用时,请考虑使用$geoWithin运算符,该运算符不对文档进行排序,而不是$nearSphere

Examples

使用 GeoJSON 指定中心点

考虑一个集合places,该集合_2 包含具有location字段并且具有2dsphere索引的文档。

然后,下面的示例返回其location距指定点至少1000米,并且距指定点最多5000米,其 Sequences 为从最近到最远:

db.places.find(
   {
     location: {
        $nearSphere: {
           $geometry: {
              type : "Point",
              coordinates : [ -73.9667, 40.78 ]
           },
           $minDistance: 1000,
           $maxDistance: 5000
        }
     }
   }
)

使用旧版坐标指定中心点

2d Index

考虑一个集合legacyPlaces,该集合包含在location字段中具有旧坐标对的文档并具有2d索引。

然后,以下示例返回从指定点起location最多为0.10弧度的文档(从最近到最远排序):

db.legacyPlaces.find(
   { location : { $nearSphere : [ -73.9667, 40.78 ], $maxDistance: 0.10 } }
)

2dsphere Index

如果集合具有2dsphere索引,则还可以指定可选的$minDistance规范。例如,以下示例返回从指定点起location弧度至少为0.0004弧度的文档,从最近到最远排序:

db.legacyPlaces.find(
   { location : { $nearSphere : [ -73.9667, 40.78 ], $minDistance: 0.0004 } }
)
首页