当前位置:Gxlcms > 数据库问题 > MongoDB 学习笔记之 地理空间索引入门

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

时间:2021-07-01 10:21:17 帮助过:27人阅读

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

 

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   

人气教程排行