Docs 菜单
Docs 主页
/
MongoDB Manual
/ / / / /

查询球面上某个点附近的位置

在此页面上

  • 关于此任务
  • 开始之前
  • 步骤
  • 了解详情

您可以查询球体上指定点附近出现的位置数据。

要查询指定点附近的位置数据,请使用 $near操作符:

db.<collection>.find( {
<location field> : {
$near : {
$geometry : {
type : "Point",
coordinates : [ <longitude>, <latitude> ]
},
$maxDistance : <distance in meters>
}
}
} )
  • 在您指定经度和纬度坐标时,请先列出经度,然后再列出纬度

    • 有效经度值介于 -180180 之间,两者均包括在内。

    • 有效纬度值介于 -9090 之间,两者均包括在内。

  • $maxDistance字段中指定距离(以为单位)。

  1. 创建一个 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 点。

  2. 要使用$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'
}
]

结果按与查询点的距离从最近到最远排序。

后退

Polygons