>  기사  >  데이터 베이스  >  Mongodb地理空间索引

Mongodb地理空间索引

WBOY
WBOY원래의
2016-06-07 15:56:521259검색

1. LBS地理空间索引 关于LBS相关项目,一般存储每个地点的经纬度的坐标, 如果要查询附近的场所,则需要建立索引来提升查询效率。 Mongodb专门针对这种查询建立了地理空间索引。 2d和2dsphere索引。 2. 创建索引 建立places集合,来存放地点, loc字段用来存

1. LBS地理空间索引

关于LBS相关项目,一般存储每个地点的经纬度的坐标, 如果要查询附近的场所,则需要建立索引来提升查询效率。 Mongodb专门针对这种查询建立了地理空间索引。 2d和2dsphere索引。

2. 创建索引

建立places集合,来存放地点, loc字段用来存放地区数据GeoJSON Point。
db.places.insert(
   {
      loc : { type: "Point", coordinates: [ -73.97, 40.77 ] },
      name: "Central Park",
      category : "Parks"
   }
)

db.places.insert(
   {
      loc : { type: "Point", coordinates: [ -73.88, 40.78 ] },
      name: "La Guardia Airport",
      category : "Airport"
   }
)
建立索引
db.places.ensureIndex( { loc : "2dsphere" } )
参数不是1或-1,为2dsphere。还可以建立组合索引。
db.places.ensureIndex( { loc : "2dsphere" , category : -1, name: 1 } )

3. 查询

$geometry表示查询的几何图片.

3.1 查询多边形范围的值

type表示类型:polygon 多边形
db.places.find( { loc :
                  { $geoWithin :
                    { $geometry :
                      { type : "Polygon" ,
                        coordinates : [ [
                                          [ 0 , 0 ] ,
                                          [ 3 , 6 ] ,
                                          [ 6 , 1 ] ,
                                          [ 0 , 0 ]
                                        ] ]
                } } } } )

3.2 查询附近的值

使用$near来查询附近的地点。
 db.places.find( { loc :
                         { $near :
                           { $geometry :
                              { type : "Point" ,
                                coordinates : [ <longitude> , <latitude> ] } ,
                             $maxDistance : <distance in meters>
                      } } } )

3.3 查询圆形内的值

查询圆时,需要指定圆心, 半径。
db.places.find( { loc :
                  { $geoWithin :
                    { $centerSphere :
                       [ [ -88 , 30 ] , 10 ]
                } } } )
[-88, 30] 为经纬度, 10为半径。
地址:http://blog.csdn.net/yonggang7/article/details/28109463
성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.