使用 2dSphere索引查找最近的点

主要步骤如下:

1、建立集合和索引。

sphere为建立的集合,sp为建立索引的字段名,我们建立的索引类型2dsphere

创建2dsphere索引命令

db.sphere.ensureIndex({"sp":"2dsphere"}),如下图

使用 2dSphere索引查找最近的点_第1张图片
Paste_Image.png

2、向集合中插入经纬度数据。

这里需要注意的是,如果我们如果用的是2dsphere索引,那么插入的应该是GeoJson数据。GeoJson的格式是 { type: ‘GeoJSON type’ , coordinates: ‘coordinates’ } 其中type指的是类型,可以是Point(本例中用的),LineString,Polygon等,coordinates是一个坐标数组。

插入Point数据

db.sphere.insert({name:"paidan",sp:{type:"Point",coordinates:[118.170995,24.530915]}})
db.sphere.insert({name:"shuanshi",sp:{type:"Point",coordinates:[118.162803,24.528942]}})
db.sphere.insert({name:"fanhu",sp:{type:"Point",coordinates:[118.15788,24.527463]}})
db.sphere.insert({name:"xiada",sp:{type:"Point",coordinates:[118.107934,24.444757]}})

3、进行查询。

介绍一下其中的参数

(1)geoNear:我们要查询的集合名称
(2)near:就是基于那个点进行搜索,这里是我们的搜索点A
(3)spherical:是个布尔值,如果为true,表示将计算实际的物理距离比如两点之间有多少km,若为false,则会基于点的单位进行计算
(4)minDistance:搜索的最小距离,这里的单位是米
(5)maxDistance:搜索的最大距离

db.runCommand({
geoNear:"sphere",
near:{type:"Point",coordinates:[118.171831,24.531186]},
spherical:true,
minDistance:0,maxDistance:40000
})

(4)结果分析
如下


使用 2dSphere索引查找最近的点_第2张图片
Paste_Image.png

在results中,每个文档都加上了一个dis字段,他表示这个点离你搜索点的距离。

还可以限制对查询的结果限制多少条,可加上num字段进行选取,如下

db.runCommand({
geoNear:"sphere",
near:{type:"Point",coordinates:[118.171831,24.531186]},
spherical:true,
minDistance:0,maxDistance:40000,
num:1
})

如下,这样就只显示一条数据了

使用 2dSphere索引查找最近的点_第3张图片
Paste_Image.png

使用php语法操作mongodb

查询
loc;
$collection=$db->sphere;

$arr = array(
    'geoNear'=>"sphere",
    'near' =>array(
        'type'=>'Point',
        'coordinates'=>array(118.171831,24.531186)
    ),
    'spherical'=>true,
    'minDistance' => 0,
    'maxDistance'=>400000,
    'num'=>3
);
$res = $db->command($arr);
echo "
";print_r($res);die;
?>

如下显示

使用 2dSphere索引查找最近的点_第4张图片
Paste_Image.png
插入数据
'fuzhou',
    'sp' => array(
        'type'=>'Point',
        'coordinates'=>array(118.672202,24.518702)//注意经纬不能使用字符串
    )
);
$db=$conn->loc;
$collection=$db->sphere;
$collection->insert($data);
die;
?>

你可能感兴趣的:(使用 2dSphere索引查找最近的点)