文档菜单
文档首页
/
MongoDB 手册
/ / / /

$nearSphere

本页内容

  • 定义
  • 行为
  • 示例
$nearSphere

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

$nearSphere 需要 地理空间索引

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

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

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

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

{
$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 查询组合。

$nearSphere运算符按照距离对文档进行排序。

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

  • 如果文档的顺序对您来说不重要,请考虑使用$geoWithin运算符,因为它返回未排序的结果。

  • $nearSphere是一个匹配执行运算符,不允许在聚合管道中使用。

从MongoDB 8.0开始,$near$nearSphere$geoNear将验证指定的GeoJSON点类型是否为Point。任何其他输入类型都将返回错误。

考虑一个包含具有location字段和具有2dsphere索引的文档的集合places

然后,以下示例返回与指定点的距离至少为1000米且最多为5000米的location,按从近到远的顺序排序。

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

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

然后,以下示例返回那些与指定点最多相距 0.10 弧度的文档,按从近到远的顺序排序

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

如果集合具有 2dsphere 索引,则还可以指定可选的 $minDistance 规范。例如,以下示例返回那些与指定点至少相距 0.0004 弧度的文档,按从近到远的顺序排序

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

返回

$near

本页内容