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 ] ] ] } } } } )
對於幾何查詢, 可以參考:
- $box
- $polygon
- $center (定義一個圓)
- $centerSphere (定義一個橢球面上的圓)