大家好,又见面了,我是全栈君,祝每个程序员都可以多学几门语言。
关于LBS相关项目,一般存储每一个地点的经纬度的坐标, 假设要查询附近的场所,则须要建立索引来提升查询效率。
Mongodb专门针对这样的查询建立了地理空间索引。
2d和2dsphere索引。
建立places集合,来存放地点,
loc字段用来存放地区数据GeoJSON Point。
db.places.insert(
{
loc : { type: "Point", coordinates: [ -73.97, 40.77 ] },
name: "Central Park",
category : "Parks"
}
)
db.places.insert(
{
loc : { type: "Point", coordinates: [ -73.88, 40.78 ] },
name: "La Guardia Airport",
category : "Airport"
}
)
建立索引
db.places.ensureIndex( { loc : "2dsphere" } )
參数不是1或-1,为2dsphere。
还能够建立组合索引。
db.places.ensureIndex( { loc : "2dsphere" , category : -1, name: 1 } )
$geometry表示查询的几何图片.
type表示类型:polygon 多边形
db.places.find( { loc :
{ $geoWithin :
{ $geometry :
{ type : "Polygon" ,
coordinates : [ [
[ 0 , 0 ] ,
[ 3 , 6 ] ,
[ 6 , 1 ] ,
[ 0 , 0 ]
] ]
} } } } )
使用$near来查询附近的地点。
db.places.find( { loc :
{ $near :
{ $geometry :
{ type : "Point" ,
coordinates : [ <longitude> , <latitude> ] } ,
$maxDistance : <distance in meters>
} } } )
查询圆时,须要指定圆心, 半径。
db.places.find( { loc :
{ $geoWithin :
{ $centerSphere :
[ [ -88 , 30 ] , 10 ]
} } } )
[-88, 30] 为经纬度, 10为半径。
地址: http://blog.csdn.net/yonggang7/article/details/28109463
发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/118844.html原文链接:https://javaforall.cn