mongodb 存储经纬度以及查询,附操作案例

来源:互联网 发布:知乎提问是匿名吗 编辑:程序博客网 时间:2024/06/09 14:05

LBS,存储每个地点的经纬度坐标,搜寻附近的地点,建立地理位置索引可提高查询效率。
mongodb地理位置索引,2d和2dsphere,对应平面和球面。
mongodb位置查询文档
实现原理:参考文章

两种索引方式

2d index:
使用2d index 能够将数据作为2维平面上的点存储起来, 在MongoDB 2.2以前 推荐使用2d index索引。
2dsphere index:
2dsphere index 支持球体的查询和计算,同时它支持数据存储为GeoJSON 和传统坐标。

3种距离单位:

米(meters)
平面单位(flat units,可以理解为经纬度的“一度”)
弧度(radians)
2d索引能同时支持centercenterSphere,
2dsphere索引支持centerSpherecenter默认是度,$centerSphere默认距离是弧度

地理位置索引-2d索引的创建方式

这里写图片描述
首先需对col里的w设置索引为’2d’,方可进行$near查询

db.location.ensureIndex({w:"2d"})  

w对应的经纬度外镶字段
创建了地理位置索引,默认mongoDB**不允许查询超过180的值**

地理位置索引-2d索引查询方式

这里写图片描述

地理位置索引-2d索引-$near

db.location.find({w:{$near:[1,1]}})

$near会返回最近的100个记录.
地理位置索引-2d索引-$near 限制返回的距离的远近,限制最远距离:限制最近距离:maxDistance单位是弧度, 地球表面1弧度距离约为6378137米, 0.001弧度距离为6378米

这里写图片描述

地理位置索引-2d索引 $geoWithin 形状的表示
由于$geoWithin是查询某个形状内的点,所以先要学会如何表示形状.
这里写图片描述
地理位置索引-2d索引 $geoWithin 查询矩形中的点

db.location.find({w:{$geoWithin:{$box:[[0,0],[3,3]]}}})db.location.find({w:{$geoWithin:{$box:[[1,1],[2,3]]}}})

地理位置索引-2d索引 $geoWithin 查询圆形中的点

db.location.find({w:{$geoWithin:{$center:[[0,0],5]}}})

地理位置索引-2d索引 $geoWithin 查询多边形中的点

db.location.find({w:{$geoWithin:{$polygon:[[0,0],[0,1],[2,5],[6,1]]}}})

地理位置索引-2d索引 geoNear

db.runCommand({geoNear:"location",near:[1,2],maxDistance:10,num:1})

这里写图片描述

地理位置索引-2dsphere索引

这里写图片描述

查询案例:

db.user.find({"geo": {$near: [118.10388605,24.48923061], $maxDistance:0.1}},{id:1, name:1, state:1, geo:1}).limit(1).pretty()

这里写图片描述

整个案例:
插入 lbs;

db.lbs.insert(      {          loc:{              type: "Point",              coordinates: [113.332264, 23.156206]          },          name: "广州东站"      }  )  db.lbs.insert(      {          loc:{              type: "Point",              coordinates: [113.330611, 23.147234]          },          name: "林和西"      }  )  db.lbs.insert(      {          loc:{              type: "Point",              coordinates: [113.328095, 23.165376]          },          name: "天平架"      }  )  

插入结果,IDE显示如下
这里写图片描述

db.lbs.ensureIndex(      {          loc: "2dsphere"      }  ) 

创建地理位置索引
这里写图片描述
创建完成之后在indexes中出现了新的索引形式即为成功
这里写图片描述

db.lbs.find(      {          loc: {              $near:{                  $geometry:{                      type: "Point",                      coordinates: [113.323568, 23.146436]                  },                  $maxDistance: 1000              }          }      }  )  

最终查询结果下:
这里写图片描述

查询更多字段时,执行:
db.lbs.find(
{
loc: {
near:{geometry:{
type: “Point”,
coordinates: [113.323568, 23.146436]
},
$maxDistance: 1000
}
}
} ,{此处添加比如:type:1,name:1}
)