On this page
$nearSphere
在本页面
Definition
$nearSphere
- 指定一个geospatial查询从最近到最远返回文档的点。 MongoDB 使用球形几何计算$nearSphere的距离。
$nearSphere 需要地理空间索引:
2dsphere定义为 GeoJSON 点的位置数据的索引
定义为旧版坐标对的位置数据的2d索引。要在GeoJSON points上使用2d索引,请在 GeoJSON 对象的
coordinates
字段上创建索引。
$nearSphere运算符可以指定GeoJSON点或旧坐标点。
要指定GeoJSON Point,请使用以下语法:
{
$nearSphere: {
$geometry: {
type : "Point",
coordinates : [ <longitude>, <latitude> ]
},
$minDistance: <distance in meters>,
$maxDistance: <distance in meters>
}
}
- 可选 $minDistance仅在查询使用2dsphere索引时可用。 $minDistance将结果限制为距中心点至少*指定距离的那些文档。
2.6 版的新功能。
- 可选 $maxDistance可用于任一索引。
要使用传统坐标指定点,请使用以下语法:
{
$nearSphere: [ <x>, <y> ],
$minDistance: <distance in radians>,
$maxDistance: <distance in radians>
}
- 可选 $minDistance仅在查询使用2dsphere索引时可用。 $minDistance将结果限制为距中心点至少*指定距离的那些文档。
2.6 版的新功能。
- 可选 $maxDistance可用于任一索引。
如果您将经度和纬度用于旧版坐标,请先指定经度,然后再指定纬度。
See also
Behavior
特殊索引限制
您不能将需要特殊geospatial index的$nearSphere运算符与需要另一个特殊索引的查询运算符或命令结合使用。例如,您不能将$nearSphere与$text查询结合使用。
分片集合限制
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 } }
)