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

地理空间索引:

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

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})

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

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