码迷,mamicode.com
首页 > 数据库 > 详细

MongoDB 学习笔记之 地理空间索引入门

时间:2017-09-09 21:00:26      阅读:235      评论:0      收藏:0      [点我收藏+]

标签:信息   es2017   很多   技术   point   ext   find   使用   png   

地理空间索引:

地理空间索引,可用于处理基于地理位置的查询。

 

Point:用于指定所在的具体位置,我们以restaurants为例:

 db.restaurants.insert({name: "Citi", loc: {type: "Point", coordinates: [52.37, 5.21]}})

db.restaurants.insert({name: "SAP", loc: {type: "Point", coordinates: [51.91, 4.41]}})

db.restaurants.insert({name: "IBM", loc: {type: "Point", coordinates: [52.36, 4.89]}})

技术分享

创建2dsphere索引:(经度默认范围是-180到180,我们修改为-500到500)

db.restaurants.ensureIndex({loc: "2dsphere"},{min: -500, max: 500})

技术分享

搜索离指定地点最大距离在40000米之内的restaurants:

 db.restaurants.find({loc: {$geoNear: {$geometry: {type: "Point", coordinates:[52.33,5.51]}, $maxDistance: 40000}}})

 技术分享

查看执行计划,发现使用了2dsphere索引: 

db.restaurants.find({loc: {$geoNear: {$geometry: {type: "Point", coordinates:[52.33,5.51]}, $maxDistance: 40000}}}).explain(true)

技术分享

 

默认情况下,使用find()函数运行查询足够了,不过MongoDB还提供了geoNear函数,它还在查询结果中提供了指定点到每个记录的距离,以及一些额外的诊断信息。

 db.runCommand({geoNear: "restaurants", near: {type: "Point", coordinates: [52.33, 5.51]}, spherical: true})

技术分享

地理空间类型和函数还有很多,但是和点的用法类似, 这里不就一一举例,如果大家在工作中使用它,可以到官网查询。

MongoDB 学习笔记之 地理空间索引入门

标签:信息   es2017   很多   技术   point   ext   find   使用   png   

原文地址:http://www.cnblogs.com/AK47Sonic/p/7499207.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!