时间:2021-07-01 10:21:17 帮助过:38人阅读
1. LBS地理空间索引 关于LBS相关项目,一般存储每个地点的经纬度的坐标, 如果要查询附近的场所,则需要建立索引来提升查询效率。 Mongodb专门针对这种查询建立了地理空间索引。 2d和2dsphere索引。 2. 创建索引 建立places集合,来存放地点, loc字段用来存
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 } )
db.places.find( { loc :
{ $geoWithin :
{ $geometry :
{ type : "Polygon" ,
coordinates : [ [
[ 0 , 0 ] ,
[ 3 , 6 ] ,
[ 6 , 1 ] ,
[ 0 , 0 ]
] ]
} } } } )
db.places.find( { loc :
{ $near :
{ $geometry :
{ type : "Point" ,
coordinates : [ , ] } ,
$maxDistance :
} } } )
db.places.find( { loc :
{ $geoWithin :
{ $centerSphere :
[ [ -88 , 30 ] , 10 ]
} } } )
[-88, 30] 为经纬度, 10为半径。