查询与 GeoJSON 对象相交的位置
您可以查询与 GeoJSON对象相交的位置数据。 示例,考虑一个存储加油站坐标的应用程序。 您可以创建一个表示公路旅行的GeoJSON 线串(LineString) ,并查询与公路旅行路线相交的加油站。
要查询与 GeoJSON 对象相交的位置数据,请使用 $geoIntersects
操作符:
db.<collection>.find( { <location field> : { $geoIntersects : { $geometry : { type : "<GeoJSON object type>", coordinates : [ <coordinates> ] } } } } )
关于此任务
在您指定经度和纬度坐标时,请先列出经度,然后再列出纬度。
有效经度值介于
-180
和180
之间,两者均包括在内。有效纬度值介于
-90
和90
之间,两者均包括在内。
如果某个位置与指定对象至少共享一个点,则该位置与该对象相交。这包括具有共用边缘的对象。
$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' } ]