“文档” 菜单
文档首页
/
MongoDB Manual
/ / / /

$nearSphere

在此页面上

  • 定义
  • 行为
  • 举例
$nearSphere

指定一个点, 地理空间查询将返回从最近到最远的文档。 MongoDB 使用球面几何计算 $nearSphere的距离。

$nearSphere 需要地理空间索引:

  • 2dsphere 索引,用于定义为 GeoJSON 点的位置数据。

  • 2d 索引,用于定义为传统坐标对的位置数据。要在 GeoJSON 点上使用 2d 索引,请在 GeoJSON 对象的 coordinates 字段上创建索引。

$nearSphere 操作符可以指定一个 GeoJSON 点或旧版坐标点。

要指定一个 GeoJSON 点,请使用以下语法:

{
$nearSphere: {
$geometry: {
type : "Point",
coordinates : [ <longitude>, <latitude> ]
},
$minDistance: <distance in meters>,
$maxDistance: <distance in meters>
}
}
  • 可选 $minDistance 会将结果限制为与中心点至少相距指定距离的文档。

  • 可选 $maxDistance 可用于任一索引。

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

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

如果使用传统坐标的经度和纬度,请先指定经度,然后再指定纬度。

不能将需要特殊地理空间索引$nearSphere 操作符与需要其他特殊索引的查询操作符或命令结合使用。例如,不能将 $nearSphere$text 查询结合使用。

在 MongoDB 4.0 之前,分片集合不支持 $nearSphere 查询。您可以使用 $geoNear 聚合阶段或 geoNear 命令。

$nearSphere 操作符按距离对文档进行排序。

  • 如果您在查询中使用了 sort() 方法,MongoDB 会再一次执行排序操作,对匹配的文档重新排序。查询大型集合时,这可能会对查询性能产生负面影响。

  • 如果文档的顺序对您来说并不重要,可以考虑改用 $geoWithin 操作符,因为该操作符会返回未排序的结果。

  • $nearSphere 是一种匹配执行操作符,不允许在聚合管道中使用。

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

然后,以下示例返回距指定点至少 1000 米、至多 5000 米(按从最近到最远排序)的 location

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

考虑一个 legacyPlaces 集合,它包含带有 location 字段中传统坐标对的文档且具有 2d 索引。

然后,以下示例返回 location 距离指定点至多 0.10 弧度的文档,按从最近到最远的顺序排列:

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

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

db.legacyPlaces.find(
{ location : { $nearSphere : [ -73.9667, 40.78 ], $minDistance: 0.0004 } }
)
← $near
$box →

在此页面上