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

主要步骤如下:

1、建立集合和索引。

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

创建2dsphere索引命令

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

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

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

(4)结果分析
如下


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
})

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

Paste_Image.png

使用php语法操作mongodb

查询
<?php
$conn = new MongoClient();
$db=$conn->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 "<pre>";print_r($res);die;
?>

如下显示

Paste_Image.png
插入数据
<?php
$data = array(
    'name'=>'fuzhou',
    'sp' => array(
        'type'=>'Point',
        'coordinates'=>array(118.672202,24.518702)//注意经纬不能使用字符串
    )
);
$db=$conn->loc;
$collection=$db->sphere;
$collection->insert($data);
die;
?>
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容