您可以查询球体表面的一个圆内的位置数据。使用这些查询返回 球形上限 内的数据。
要查询球体上一个圆内的位置数据,请使用 $geoWithin和$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" } ] )
步骤
要查询collection,请使用$geoWithin和$centerSphere操作符:
db.places.find( { loc: { $geoWithin: { $centerSphere: [ [ -1.76, 51.16 ], 10 / 6378.1 ] } } } )
该查询返回loc字段位于经度-1.76 、纬度51.16的点的 10 公里半径内的文档。
输出:
[ { _id: ObjectId("63fd205e4a08b5e248c03e32"), loc: { type: 'Point', coordinates: [ -1.83, 51.18 ] }, name: 'Stonehenge', category: 'Monument' } ]