MongoDB空间索引详解
MongoDB是一个非常优秀的NoSQL数据库,也是最接近关系型数据库的。无论是索引还是数据库CURD操作,都是非常相似的。Mongodb专门针对这种查询建立了地理空间索引。 如果要根据运用层定位的坐标,查询附近的场所,则需要建立索引来提升查询效率,这样的场景用MongoDB地理空间索引就非常合适了。
1. 在MongoDB中创建结合插入数据,并建立2d空间索引。
1 2 3 4 5 6 7 8 9 10 11 | db.location.insert({ point: [ -73.82, 40.79 ] , name: "Park" }) db.location.insert({ point: [ -73.85, 40.76 ] , name: "Airport" }) db.location.ensureIndex( { point: "2d" } ) 参数不是1或-1,为2d。还可以建立组合索引。 db.location.ensureIndex( { point: "2d" , name: 1 } ) |
2、MongoDB运用空间索引查询多边形范围的值,MongoDB的$geoWithin 操作符支持的形状有$box(矩形),$center(圆形),$polygon(多边形,包括凹多边形和凸多边形)。所有的范围查询,默认是包含边界的。
1 2 3 4 5 6 7 8 9 10 11 | db.location.find( { point: { $geoWithin : { $geometry : { type : "Polygon" , coordinates : [ [ [ 0 , 0 ] , [ 3 , 6 ] , [ 6 , 1 ] , [ 0 , 0 ] ] ] } } } } ) |
3、MongoDB运用空间索引查询某个点附近的值。
1 | db.location.find( {point: {$near : [50,50]}} ) |
4、MongoDB运用空间索引查询圆形内的值,需要指定圆心, 半径。
1 2 3 4 5 6 | db.location.find( { point: { $geoWithin : { $center: [ [ -88 , 30 ] , 10 ] } } } ) [-88, 30] 为经纬度, 10为半径。 |
2019年5月5日 下午8:17
好文章!666,学习了
2019年5月10日 下午4:50
看过了。很好很强大。