MongoDB采用geoJson格式来存储常见的点,线,面的几何信息.
点:db.points.insert({"pt":{type:"Point",coordinates:[10,10]}})
线:db.lines.insert({"ln":{type:"LineString",coordinates:[[10,10],[20,20]]}})
面:db.polygons.insert({"pg":{type:"Polygon",coordinates:[[[5,5],[5,15],[15,15],[15,5],[5,5]]]}})
常见的空间查找操作:
1.包含$geoWithin
db.points.find({"pt":{$geoWithin:{$geometry:{type:"Polygon",coordinates:[[[5,5],[5,15],[15,15],[15,5],[5,5]]]}}}})
圆形查询: db.points.find({"pt":{$geoWithin:{$centerSphere:[[6,6](圆心),2(半径)]}})
2.相交$geoIntersects
db.lines.find({"ln":{$geoIntersects:{$geometry:{type:"Polygon",coordinates:[[[5,5],[5,15],[15,15],[15,5],[5,5]]]}}}})
3.点查询$near
先给查询的字段建立一个2dsphere索引:db.points.ensureIndex({"pt":"2dsphere"})
执行周边查询:
db.points.find({"pt":{$near:{$geometry:{type:"Point",coordinates:[5.01,5.01]},$maxDistance:1000000(米)}}})
4.周边查询geonear
先要建立空间索引,再执行周边查询:
db.runCommand({geoNear:"points",near:{type:"Point",coordinates:[5.01,5.01]},spherical:true})