MongoDB空间查询

MongoDB 在2.4版本以后,对空间查询支持更友好了,下面简介一下$geoWithin,文章翻译自:http://docs.mongodb.org/manual/reference/operator/geoWithin/#op._S_geoWithin

$geoWithin

      在MongoDB2.4中使用$geoWithin操作符(或称函数,下亦同)替代废弃的$within操作符。$geoWithin操作符是一个支持查询在一个几何要素内(完全在这几何要素内)的另一个特定的点、线或者其他几何类型要素。$geoWithin操作符支持GeoJSON作为查询条件。$geoWithin操作符不返回排序的结果集。它的查询效率要比支持排序的$near或者$nearSphere操作符快。

     $geoWithin支持空间索引。和2.2.3版本$geoWithin不同的是,它需要空间索引,这样可以提升空间查询效率。

     查询一个多边形内部所有要素的语法如下:

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

需要特别声明的是:坐标的顺序必须这样,“经度,维度”。

下面的例子是查询一个多边形范围内所有索引的地名要素。

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

对于几何查询, 可以参考:

原文地址:https://www.cnblogs.com/likehua/p/3024625.html