查询球体上在圆内的位置
您可以查询球体表面上位于圆内的位置数据。使用这些查询来返回位于球冠内的数据。
要查询球体上的圆内的位置数据,请使用 $geoWithin
with$centerSphere
运算符。在 $centerSphere
运算符中,指定要查询的圆的坐标和半径:
db.<collection>.find( {
<location field> : {
$geoWithin : {
$centerSphere: [
[ <longitude>, <latitude> ],
<radius>
]
}
}
} )
关于此任务
- 当您指定经度和纬度坐标时,请先列出 经度,然后列出纬度。
- 有效的经度值介于
-180
和之间180
(包含两者)。 - 有效的纬度值介于
-90
和之间90
(包含两者)。
- 有效的经度值介于
- 在运算符中,以弧度
$centerSphere
指定圆的半径 。要将其他单位与弧度相互转换,请参阅将球面运算符的距离转换为弧度。- 此示例计算以公里为单位的距离。要将公里转换为弧度,请将公里值除以
6378.1
。
- 此示例计算以公里为单位的距离。要将公里转换为弧度,请将公里值除以
$geoWithin
不需要地理空间索引。但是,地理空间索引可以提高查询性能。仅2dsphere地理空间索引支持$geoWithin
. 有关详细信息,请参阅创建 2dsphere 索引。
在你开始之前
创建一个places
包含这些文档的集合:
db.places.insertMany( [
{
loc: { type: "Point", coordinates: [ -73.97, 40.77 ] },
name: "Central Park",
category : "Park"
},
{
loc: { type: "Point", coordinates: [ -73.88, 40.78 ] },
name: "La Guardia Airport",
category: "Airport"
},
{
loc: { type: "Point", coordinates: [ -1.83, 51.18 ] },
name: "Stonehenge",
category : "Monument"
}
] )
过程
要查询集合,请$geoWithin
与$centerSphere
运算符一起使用:
db.places.find( {
loc: {
$geoWithin: {
$centerSphere: [
[ -1.76, 51.16 ],
10 / 6378.1
]
}
}
} )
该查询返回字段位于 longitude , latitude loc
点的 10 公里半径范围内的文档。-1.76``51.16
输出:
[
{
_id: ObjectId("63fd205e4a08b5e248c03e32"),
loc: { type: 'Point', coordinates: [ -1.83, 51.18 ] },
name: 'Stonehenge',
category: 'Monument'
}
]