基于MongoDB位置查询GEO信息

MongoDB目前支持二维的地图查询,查询区域包括圆形与矩形,距离单位包括MILES,KILOMETERS,NEUTRAL,下面的示例演示距离单位为NEUTRAL,而实际生产应用中则会用到MILES与KILOMETERS.

MongoDB示例

首先定义一个位置集合,给定a,b,c,d节点.

> db.createCollection("location")
{ "ok" : 1 }
> db.location.save( {_id: "A", position: [0.1, -0.1],title:"位置1"} )
> db.location.save( {_id: "B", position: [1.0, 1.0]} ,title:"位置2")
> db.location.save( {_id: "C", position: [0.5, 0.5]},title:"位置3" )
> db.location.save( {_id: "D", position: [-0.5, -0.5]},title:"位置4" )

接着指定location索引

db.location.ensureIndex( {position: "2d"} )

现在我们可以进行简单的GEO查询

查询point(0,0),半径0.7附近的点

> db.location.find( {position: { $near: [0,0], $maxDistance: 0.7  } } )
Result:
{ "_id" : "A", "position" : [ 0.1, -0.1 ] ,title:"位置1"}

查询point(0,0),半径0.75附近的点

> db.location.find( {position: { $near: [0,0], $maxDistance: 0.75  } } )
Result:
{ "_id" : "A", "position" : [ 0.1, -0.1 ] ,title:"位置1"}
{ "_id" : "C", "position" : [ 0.5, 0.5 ] ,title:"位置3"}
{ "_id" : "D", "position" : [ -0.5, -0.5 ],title:"位置4" }

我们可以看到半径不一样,查询出的点也不一样,因为c点坐标为[0.5,0.5],c至圆点的距离根据勾股定理可得出Math.sqrt(0.25 +0.25) ≈ 0.707,所以最大距离0.7时查找不到你要的点.

查询[0.25, 0.25], [1.0,1.0]区域附近的点

> db.location.find( {position: { $within: { $box: [ [0.25, 0.25], [1.0,1.0] ] }  } } )
{ "_id" : "C", "position" : [ 0.5, 0.5 ],title:"位置3" }
{ "_id" : "B", "position" : [ 1, 1 ] ,title:"位置4"}

 

转载于:https://my.oschina.net/u/200350/blog/886682

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值