2d索引和sdsphere索引的计算方式不一样
2d 索引 (平面索引)
1、创建方式
db.collection.createIndex({geom:"2d"})
geom:坐标字段,取值范围 经度[-180,180] 维度[-90,90]
2、查询方式
$near:查询距离点最近的点, 默认返回100个。
db.collection.find({geom:{$near:[118,34]}})
db.collection.find({geom:{$near:[118,34],$maxDistance:10}}) // 最大距离
$geomWithin:查询某个形状内的点
$box :矩形
{$box:[[<X1>,<Y1>],[<X2>,<Y2>]]} 左边界,右边界
db.collection.find({geom:{$geoWithin:{$box:[[0,0],[3,3]]}}})
$center :圆形
{$center:[[<X1>,<Y1>],r]} r:半径
db.collection.find({geom:{$geoWithin:{$center:[[0,0],10]}}})
$polygon : 多边形
{$polygon:[[<X1>,<Y1>],[<X1>,<Y1>],[<X1>,<Y1>],[<X1>,<Y1>]]} 坐标数组
db.collection.find({geom:{$geoWithin:{$polygon:[[0,0],[0,1],[1,1],[1,0],]}}})
geoNear查询
命令:db.runCommand({
geoNear:<collection>, //集合名称
near:[x,y], //坐标
minDistance:(对2d索引无效)
maxDistance:10 //最大距离
num:10 //限制返回的数据
})
2dsphere索引(球面地理位置索引)
1、创建方式
db.collection.createIndex({geom:"2dsphere"})
2、位置表示方式
GeoJSON:描述一个点、线、多边形等形状
3、 格式:
{type:"",coordinates:[<coordinates>]}
查询方式和2d索引查询方式类似
支持$minDistance与$maxDistance
示例: