mongodb 2dsphere 两种查寻附近坐标的方法

一、集合重插以下数据

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


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值