MongoDB2.4支持空间数据 点线面
2dsphere索引--2.4版本的新特色
2dsphere索引支持地球球面上的空间体计算的查询,支持以GeoJSON存储的对象和以传统坐标对存储的对象,但是传统坐标对存储的对象要转换成GeoJSON的格式才受支持。2dsphere索引支持所有MongoDB的地理空间查询:包容,交叉和领近。
组合2dsphere索引可以把空间字段和非空间字段在一个collection文档中关联起来,不可以随意安排组合这些字段。
MongoDB2.4中参考参考椭球体的基准是WGS84. 坐标轴的顺序是经度,纬度。
注意:MongoDB2.4中每个集合只容许建立一个空间索引。
注意:分片的时候你可以用2dsphere索引当做shard key。但是,您可以通过使用一个不同的字段的键,创建和维护地理空间索引分片收集碎片。
GeoJSON对象的存储
mongoDB支持一下几类GeoJSON对象:
要在GeoJSON对象上建立索引,你需要把数据存在你命名的location字段中。这个location字段包含一个GeoJSON对象类型域和一个坐标域。记住确保是经度在前,纬度在后。
使用一下语法:
{ <location field> : { type : "<GeoJSON type>" ,
coordinates : <coordinates>
} }
点:
{ loc : { type : "Point" ,
coordinates : [ 40, 5 ]
} }
线:
{ loc : { type : "LineString" ,
coordinates : [ [ 40 , 5 ] , [ 41 , 6 ] ]
} }
面:
{ loc :
{ type : "Polygon" ,
coordinates : [ [ [ 0 , 0 ] , [ 3 , 6 ] , [ 6 , 1 ] , [ 0 , 0 ] ] ]
} }
记住面至少有4个点,起始点和端点一致保证闭合。
包含多个ring的面:
{ loc : { type : "Polygon" , coordinates : [ [ [ 0 , 0 ] , [ 3 , 6 ] , [ 6 , 1 ] , [ 0 , 0 ] ], [ [ 2 , 2 ] , [ 3 , 3 ] , [ 4 , 2 ] , [ 2 , 2 ] ] ] } }
这种类型确保最外面的ring在开始,不相交,其他的ring包含在最外面的ring中。
创建2dshpere索引
通过ensureIndex()方法为GeoJSON格式的数据建立空间索引,并指定集合中的定位域给2dshpere。2dshpere也可以是一个组合的索引( compound index),他不需要把定位域放在索引域中的第一个。
创建索引的语法:
db.points.ensureIndex( { <location field> : "2dsphere" } )
db.points.ensureIndex( { loc : "2dsphere" } )
db.points.ensureIndex( { loc : "2dsphere" , type : 1 } )
db.points.ensureIndex( { rating : 1 , loc : "2dsphere" } )
db.points.ensureIndex( { loc : "2dsphere" , rating : 1 , category : -1 } )
在2dsphere 索引上进行查询
db.<collection>.find( { <location field> :
{ $geoWithin :
{ $geometry :
{ type : "Polygon" ,
coordinates : [ <coordinates> ]
} } } } )
实例:
db.places.find( { loc :
{ $geoWithin :
{ $geometry :
{ type : "Polygon" ,
coordinates : [ [
[ 0 , 0 ] ,
[ 3 , 6 ] ,
[ 6 , 1 ] ,
[ 0 , 0 ]
] ]
} } } } )
其他查询类似。

浙公网安备 33010602011771号