Docs 菜单
Docs 主页
/
MongoDB Manual
/ /

查询2dsphere 索引

在此页面上

  • 以多边形为界的 GeoJSON 对象
  • GeoJSON 对象的交集
  • GeoJSON point的邻近度
  • 球体上定义的圆内的点

以下部分介绍了2dsphere索引支持的查询。

$geoWithin操作符查询在 GeoJSON 多边形中找到的位置数据。您的位置数据必须以 GeoJSON 格式存储。使用以下语法:

db.<collection>.find( { <location field> :
{ $geoWithin :
{ $geometry :
{ type : "Polygon" ,
coordinates : [ <coordinates> ]
} } } } )

以下示例选择完全存在于 GeoJSON 多边形内的所有点和形状:

db.places.find( { loc :
{ $geoWithin :
{ $geometry :
{ type : "Polygon" ,
coordinates : [ [
[ 0 , 0 ] ,
[ 3 , 6 ] ,
[ 6 , 1 ] ,
[ 0 , 0 ]
] ]
} } } } )

$geoIntersects操作符查询与指定 GeoJSON 对象相交的位置。 如果交集非空,则某个位置与对象相交。 这包括具有共享边缘的文档。

$geoIntersects操作符使用以下语法:

db.<collection>.find( { <location field> :
{ $geoIntersects :
{ $geometry :
{ type : "<GeoJSON object type>" ,
coordinates : [ <coordinates> ]
} } } } )

以下示例使用$geoIntersects选择与coordinates数组定义的多边形相交的所有索引点和形状。

db.places.find( { loc :
{ $geoIntersects :
{ $geometry :
{ type : "Polygon" ,
coordinates: [ [
[ 0 , 0 ] ,
[ 3 , 6 ] ,
[ 6 , 1 ] ,
[ 0 , 0 ]
] ]
} } } } )

邻近度查询返回距离定义点最近的点,并按距离对结果排序。 针对 GeoJSON 数据的邻近查询需要2dsphere索引。

要查询与 GeoJSON point 的邻近度,请使用$near操作符。距离以米为单位。

$near使用以下语法:

db.<collection>.find( { <location field> :
{ $near :
{ $geometry :
{ type : "Point" ,
coordinates : [ <longitude> , <latitude> ] } ,
$maxDistance : <distance in meters>
} } } )

有关示例,请参阅$near

另请参阅$nearSphere操作符和$geoNear聚合管道阶段。

要选择球体上“球冠”中的所有网格坐标,请使用$geoWithin$centerSphere操作符。 指定一个包含以下内容的数组:

  • 圆中心点的网格坐标

  • 以弧度为单位测量的圆的半径。 要计算弧度,请参阅使用球面几何图形计算距离。

使用以下语法:

db.<collection>.find( { <location field> :
{ $geoWithin :
{ $centerSphere :
[ [ <x>, <y> ] , <radius> ] }
} } )

以下示例查询网格坐标并返回经度88 W和纬度30 N的 10 英里半径内的所有文档。 该示例通过除以近似地球赤道半径 3963.2 英里,将距离 10 英里转换为弧度:

db.places.find( { loc :
{ $geoWithin :
{ $centerSphere :
[ [ -88 , 30 ] , 10 / 3963.2 ]
} } } )

后退

2dsphere