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

查询与 GeoJSON 对象相交的位置

在此页面上

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

您可以查询与 GeoJSON对象相交的位置数据。 示例,考虑一个存储加油站坐标的应用程序。 您可以创建一个表示公路旅行的GeoJSON 线串(LineString) ,并查询与公路旅行路线相交的加油站。

要查询与 GeoJSON 对象相交的位置数据,请使用 $geoIntersects操作符:

db.<collection>.find( {
<location field> : {
$geoIntersects : {
$geometry : {
type : "<GeoJSON object type>",
coordinates : [ <coordinates> ]
}
}
}
} )
  • 在您指定经度和纬度坐标时,请先列出经度,然后再列出纬度

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

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

  • 如果某个位置与指定对象至少共享一个点,则该位置与该对象相交。这包括具有共用边缘的对象。

  • $geoIntersects 不需要地理空间索引。 但是,地理空间索引可提高查询性能。 只有2dsphere地理空间索引支持$geoIntersects 。 有关更多信息,请参阅创建 2dsphere 索引。

创建一个 gasStations 集合,其中包含以下文档:

db.gasStations.insertMany( [
{
loc: { type: "Point", coordinates: [ -106.31, 35.65 ] },
state: "New Mexico",
country: "United States",
name: "Horizons Gas Station"
},
{
loc: { type: "Point", coordinates: [ -122.62, 40.75 ] },
state: "California",
country: "United States",
name: "Car and Truck Rest Area"
},
{
loc: { type: "Point", coordinates: [ -72.71, 44.15 ] },
state: "Vermont",
country: "United States",
name: "Ready Gas and Snacks"
}
] )

以下$geoIntersects查询指定包含四个点的LineString ,并返回与直线相交的文档:

db.gasStations.find( {
loc: {
$geoIntersects: {
$geometry: {
type: "LineString",
coordinates: [
[ -105.82, 33.87 ],
[ -106.01, 34.09 ],
[ -106.31, 35.65 ],
[ -107.39, 35.98 ]
]
}
}
}
} )

输出:

[
{
_id: ObjectId("63f658d45e5eefbdfef81ca4"),
loc: { type: 'Point', coordinates: [ -106.31, 35.65 ] },
state: 'New Mexico',
country: 'United States',
name: 'Horizons Gas Station'
}
]

后退

球体