Mongodb地理空间索引

1. LBS地理空间索引


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

2. 创建索引


建立places集合,来存放地点,
loc字段用来存放地区数据GeoJSON Point。
[plain]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. db.places.insert(  
  2.    {  
  3.       loc : { type: "Point", coordinates: [ -73.97, 40.77 ] },  
  4.       name: "Central Park",  
  5.       category : "Parks"  
  6.    }  
  7. )  
  8.   
  9. db.places.insert(  
  10.    {  
  11.       loc : { type: "Point", coordinates: [ -73.88, 40.78 ] },  
  12.       name: "La Guardia Airport",  
  13.       category : "Airport"  
  14.    }  
  15. )  
建立索引
[plain]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. db.places.ensureIndex( { loc : "2dsphere" } )  
参数不是1或-1,为2dsphere。
还可以建立组合索引。
[plain]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. db.places.ensureIndex( { loc : "2dsphere" , category : -1, name: 1 } )  

3. 查询


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

3.1 查询多边形范围的值


type表示类型:polygon 多边形
[plain]  view plain copy 在CODE上查看代码片 派生到我的代码片
  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.                 } } } } )  

3.2 查询附近的值


使用$near来查询附近的地点。
[plain]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. db.places.find( { loc :  
  2.                         { $near :  
  3.                           { $geometry :  
  4.                              { type : "Point" ,  
  5.                                coordinates : [ <longitude> , <latitude> ] } ,  
  6.                             $maxDistance : <distance in meters>  
  7.                      } } } )  

3.3 查询圆形内的值


查询圆时,需要指定圆心, 半径。
[plain]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. db.places.find( { loc :  
  2.                   { $geoWithin :  
  3.                     { $centerSphere :  
  4.                        [ [ -88 , 30 ] , 10 ]  
  5.                 } } } )  
[-88, 30] 为经纬度,  10为半径。

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值