查询球面上某个点附近的位置
您可以查询球体上指定点附近出现的位置数据。
要查询指定点附近的位置数据,请使用 $near
操作符:
db.<collection>.find( { <location field> : { $near : { $geometry : { type : "Point", coordinates : [ <longitude>, <latitude> ] }, $maxDistance : <distance in meters> } } } )
关于此任务
在您指定经度和纬度坐标时,请先列出经度,然后再列出纬度。
有效经度值介于
-180
和180
之间,两者均包括在内。有效纬度值介于
-90
和90
之间,两者均包括在内。
在
$maxDistance
字段中指定距离(以米为单位)。
开始之前
创建一个
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" } ] ) loc
字段中的值是GeoJSON 点。要使用
$near
操作符查询位置数据,您必须在包含位置数据的字段上创建地理空间索引。在
loc
字段上创建2 dsphere索引:db.places.createIndex( { "loc": "2dsphere" } )
步骤
使用$near
查询集合。 以下$near
查询将返回在位于[ -73.92, 40.78 ]
的GeoJSON point的5000米范围内具有loc
字段的文档:
db.places.find( { loc: { $near: { $geometry: { type: "Point", coordinates: [ -73.92, 40.78 ] }, $maxDistance : 5000 } } } )
输出:
[ { _id: ObjectId("63f7c3b15e5eefbdfef81cab"), loc: { type: 'Point', coordinates: [ -73.88, 40.78 ] }, name: 'La Guardia Airport', category: 'Airport' }, { _id: ObjectId("63f7c3b15e5eefbdfef81caa"), loc: { type: 'Point', coordinates: [ -73.97, 40.77 ] }, name: 'Central Park', category: 'Park' } ]
结果按与查询点的距离从最近到最远排序。