MongoDB——索引类型之地理空间索引(Geospatial Index)

x33g5p2x  于2022-05-05 转载在 其他  
字(0.9k)|赞(0)|评价(0)|浏览(313)

一、MongoDB官网地址

二、地理空间索引(Geospatial Index)

2.1、地理空间索引(Geospatial Index)的概述

  • MongoDB为地理空间检索提供了非常方便的功能。地理空间索引(2dsphereindex)就是专门用于实现位置检索的一种特殊索引。

2.2、地理空间索引(Geospatial Index)的示例

示例需求:MongoDB实现“查询附近商家"

2.2.1、数据准备
  • 准备数据集,执行脚本
db.restaurant.insert({
 restaurantId: 0,
 restaurantName:"兰州牛肉面",
 location : {
   type: "Point",
   coordinates: [ -73.97, 40.77 ]
 }
})

  • 查看初始化的数据
> db.restaurant.find()

2.2.2、创建地理空间索引(Geospatial Index)
  • 创建一个2dsphere索引
> db.restaurant.createIndex({location : "2dsphere"})

  • 查看创建的2dsphere索引
> db.restaurant.getIndexes()

2.2.3、查询附近10000米商家信息
  • 查询附近10000米商家信息
db.restaurant.find( {
 location:{
   $near :{
     $geometry :{
       type : "Point" ,
       coordinates : [ -73.88, 40.78 ]
     } ,
     $maxDistance:10000
   }
 }
} )

  • 语法解释
操作符解释
$near查询操作符,用于实现附近商家的检索,返回数据结果会按距离排序。
$geometry用于指定一个GeoJSON格式的地理空间对象
type=Point表示地理坐标点
coordinates表示用户当前所在的经纬度位置
$maxDistance限定了最大距离,单位是米

相关文章