1.创建lbs集合存放地点坐标
方式一:
db.lbs.insert(
{
loc:{
type: "Point",
coordinates: [113.330611, 23.147234]
},
name: "林和西"
}
)
db.lbs.insert(
{
loc:{
type: "Point",
coordinates: [113.328095, 23.165376]
},
name: "天平架"
}
)
方式二:
db.collection.insert({location:[lng,lat],title:'test title'})
2.创建地理位置索引
db.lbs.ensureIndex(
{
loc: "2dsphere"
}
)
3.查询附近的坐标
当前位置为:时代广场,
坐标:113.323568, 23.146436
搜寻附近一公里内的点,由近到远排序
方式一:
db.lbs.find(
{
loc: {
$near:{
$geometry:{
type: "Point",
coordinates: [113.323568, 23.146436]
},
$maxDistance: 1000
}
}
}
)
方式二:
db.collection.find(
{
location:
{
$geoWithin:
{
$centerSphere: [ [lng, lat], 检索半径]
}
}
}
)
方式三:
db.collection.find(
{
location:
{
$near:
[lng, lat]
}
}
)