查询一个2dsphere索引

    在本页面

    以下各节描述了2dsphere索引支持的查询。

    多边形绑定的GeoJSON对象

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

    1. db.<collection>.find( { <location field> :
    2. { $geoWithin :
    3. { $geometry :
    4. { type : "Polygon" ,
    5. coordinates : [ <coordinates> ]
    6. } } } } )

    下面的例子选择了全部存在于GeoJSON多边形中的所有点和形状:

    1. db.places.find( { loc :
    2. { $geoWithin :
    3. { $geometry :
    4. { type : "Polygon" ,
    5. coordinates : [ [
    6. [ 0 , 0 ] ,
    7. [ 3 , 6 ] ,
    8. [ 6 , 1 ] ,
    9. [ 0 , 0 ]
    10. ] ]
    11. } } } } )

    GeoJSON对象的交集

    $geoIntersects操作符查询与指定GeoJSON对象相交的位置。如果交点非空,则该位置与该对象相交。这包括具有共享优势的文档。

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

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

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

    1. db.places.find( { loc :
    2. { $geoIntersects :
    3. { $geometry :
    4. { type : "Polygon" ,
    5. coordinates: [ [
    6. [ 0 , 0 ] ,
    7. [ 3 , 6 ] ,
    8. [ 6 , 1 ] ,
    9. [ 0 , 0 ]
    10. ] ]
    11. } } } } )

    接近GeoJSON点

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

    要查询与GeoJSON点的接近程度,请使用任一 $near运算符。距离以米为单位。

    $near使用的语法如下:

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

    有关示例,请参见$near

    参见$nearSphere操作符和:pipeline:$geoNear聚合管道阶段。

    球体上定义的圆内的点

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

    使用以下语法:

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

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

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

    译者:杨帅

    参见

    原文 - Query a 2dsphere Index