一、集合重插以下数据
db.mapinfo.insert({"address" : "南京 禄口国际机场","loc" : { "type": "Point", "coordinates": [118.783799,31.979234]}})
db.mapinfo.insert({"address" : "南京 浦口公园","loc" : { "type": "Point", "coordinates": [118.639523,32.070078]}})
db.mapinfo.insert({"address" : "南京 火车站","loc" : { "type": "Point", "coordinates": [118.803032,32.09248]}})
db.mapinfo.insert({"address" : "南京 新街口","loc" : { "type": "Point", "coordinates": [118.790611,32.047616]}})
db.mapinfo.insert({"address" : "南京 张府园","loc" : { "type": "Point", "coordinates": [118.790427,32.03722]}})
db.mapinfo.insert({"address" : "南京 三山街","loc" : { "type": "Point", "coordinates": [118.788135,32.029064]}})
二、建立索引
索引格式为 GeoJSON 一般不要修改
GeoJSON :{"type": "", "coordinates":[....] }
db.mapinfo.ensureIndex( { loc : "2dsphere" } )
三、搜索附近点两种方法
db.mapinfo.find({
"loc" : {
"$near" : {
"$geometry" : {
"type" : "Point", "coordinates" : [118.783799, 31.979234]
}, "$maxDistance" : 5000
}
}
}).limit(10);
这种方法可以返回的由近及远的点,但是不能获取距离
db.runCommand( {
geoNear: "mapinfo" ,
near: { type: "Point" , coordinates: [118.783799, 31.979234] } ,
spherical: true,
limit:1
})
这种方法更加灵活,可以返回距离,还可以指定查询条件等。更多属性可以参考
http://www.mongoing.com/docs/reference/command/geoNear.html#dbcmd.geoNear