作者:matrix 被围观: 3,727 次 发布时间:2018-11-26 分类:零零星星 | 无评论 »
这是一个创建于 1375 天前的主题,其中的信息可能已经有所发展或是发生改变。
mongoDb自带了地理空间索引,使用2dsphere
索引类型 可以存储GeoJSON格式数据 指定点、线和多边形。
mongodb数据
{
"_id" : ObjectId("5bf04829c6671064f9039dd0"),
"order_info" : {
"survey_coordinate" : {
"type" : "Point",
"coordinates" : [
105.431,
42.009
],
"name":"XXXXX街道办"
}
}
}
order_info.survey_coordinate字段为需要存储的数据
type:Point 点
coordinates 经纬度信息: longitude, latitude代表经度, 纬度
name为附加自定的存储名称字段
参考:
mongodb官方文档:https://docs.mongodb.com/manual/reference/geojson/
手动创建
db.order.ensureIndex( {"order_info.survey_coordinate" : "2dsphere"} )
//联合索引 如: db.order.createIndex( {"order_info.survey_coordinate" : "2dsphere","category" : -1, name: 1 } )
// 指定索引名称:db.order.createIndex( {"order_info.survey_coordinate" : "2dsphere"},{name:"locc"} )
参考:
http://www.runoob.com/mongodb/mongodb-indexing.html
代码创建
后来专门去找了下php下代码的操作,翻看各种TP文档无果,还是Google靠谱。php官方文档中
ThinkPHP5.0 参考
$mongodb;//mongodb对象为 think\db\Connection https://www.kancloud.cn/manual/thinkphp5/167865
//创建索引
$command = new \MongoDB\Driver\Command([
'createIndexes' => 'order',//给哪个集合创建索引
'indexes' => [[
'name' => 'order_info_loc_2dsphere',//索引名称
'key' => ['order_info.survey_coordinate' => '2dsphere']//索引的字段 索引类型
]]
]);
$result = $mongodb->command($command);
//首次创建返回数据
// /vagrant/saasSystem/thinkphp/library/think/Debug.php:193:
//array (size=1)
// 0 =>
// array (size=4)
// 'createdCollectionAutomatically' => boolean false
// 'numIndexesBefore' => int 1
// 'numIndexesAfter' => int 2
// 'ok' => float 1
//0.322759s ShowPageTrace
//重复创建返回数据
// /vagrant/saasSystem/thinkphp/library/think/Debug.php:193:
//array (size=1)
// 0 =>
// array (size=5)
// 'createdCollectionAutomatically' => boolean false
// 'numIndexesBefore' => int 2
// 'numIndexesAfter' => int 2
// 'note' => string 'all indexes already exist' (length=25)
// 'ok' => float 1
halt($result);
参考:
http://php.net/manual/en/mongocollection.createindex.php#119584
runCommand执行
db.runCommand( {
geoNear: "order" , //存在2dsphere索引的集合名称
near: { type: "Point" , coordinates: [118.783799, 31.979234] } ,
spherical: true,
limit:1,
})
find
db.order.find({"order_info.survey_coordinate" : { "$near" : { "$geometry" : { "type" : "Point", "coordinates" : [118.783799, 31.979234] } } } })
参考: