mongodb 地理位置查询实例

为了能用mongdodb的地理信息查询功能,插入集合的文档需要按如下格式存入:

"loc":{"type":"Point","coordinates":[经度,维度]}

loc名字可以自定义,值的格式必须按mongodb固定格式。 

将如下3个文档插入集合geo_test

{"name":"shanghai","loc":{"type":"Point","coordinates":[121,30]}}

{"name":"suzhou","loc":{"type":"Point","coordinates":[123,33]}}

{"name":"beijin","loc":{"type":"Point","coordinates":[118,40]}}

并且对loc建2dsphere索引

db.geo_test.createIndex("loc":"2dsphere")

查询一个矩形框内的点:

db.geo_test.find({"loc":{"$within":{"$box":[[120,20],[123,32]]}}})

$box的参数第一个是左下角坐标,第二个是右上角坐标

查询一个圆内的点

db.geo_test.find({"loc":{"$within":{"$center":[[121,22],13]}}})

$center的第一个参数是圆点坐标,第二个参数是半径,半径单位为坐标系使用的单位。

查一个多边形内的点

db.geo_test.find({"loc":{"$within":{"$polygon":[[120,20],[120,32],[123,35],[123,18]]}}})

查询距离某点距离在一个范围内文档

db.geo_test.find({"loc":{$near:{$geometry: { type: "Point", coordinates: [ 123, 31 ] },$minDistance: 10000,$maxDistance: 500000}}})

距离单位为米

你可能感兴趣的:(mongodb 地理位置查询实例)