目录
一、MongoDB官网地址
- 一、MongoDB官网地址
- 二、地理空间索引(Geospatial Index)
- 2.1、地理空间索引(Geospatial Index)的概述
- 2.2、地理空间索引(Geospatial Index)的示例
- 2.2.1、数据准备
- 2.2.2、创建地理空间索引(Geospatial Index)
- 2.2.3、查询附近10000米商家信息
- MongoDB官网地址:https://www.mongodb.com/docs/manual/core/index-single/
- MongoDB为地理空间检索提供了非常方便的功能。地理空间索引(2dsphereindex)就是专门用于实现位置检索的一种特殊索引。
示例需求:MongoDB实现“查询附近商家"
2.2.1、数据准备-
准备数据集,执行脚本
db.restaurant.insert({ restaurantId: 0, restaurantName:"兰州牛肉面", location : { type: "Point", coordinates: [ -73.97, 40.77 ] } })
-
查看初始化的数据
> db.restaurant.find()
-
创建一个2dsphere索引
> db.restaurant.createIndex({location : "2dsphere"})
-
查看创建的2dsphere索引
> db.restaurant.getIndexes()
-
查询附近10000米商家信息
db.restaurant.find( { location:{ $near :{ $geometry :{ type : "Point" , coordinates : [ -73.88, 40.78 ] } , $maxDistance:10000 } } } )
-
语法解释
操作符解释$near查询操作符,用于实现附近商家的检索,返回数据结果会按距离排序。$geometry用于指定一个GeoJSON格式的地理空间对象type=Point表示地理坐标点coordinates表示用户当前所在的经纬度位置$maxDistance限定了最大距离,单位是米