存储MongoDb的经纬度数据实现空间索引

作者:matrix 发布时间:2018 年 11 月 26 日 分类:零零星星

数据存储

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为附加自定的存储名称字段

参考:
http://geojson.org/
mongodb官方文档:https://docs.mongodb.com/manual/reference/geojson/

添加索引

  1. 手动创建
    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

  2. 代码创建

    后来专门去找了下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

数据查询

  1. runCommand执行

    db.runCommand( {
       geoNear: "order" , //存在2dsphere索引的集合名称
       near: { type: "Point" , coordinates: [118.783799, 31.979234] } ,
       spherical: true,
       limit:1,
    }) 
    
  2. find
    db.order.find({"order_info.survey_coordinate" : { "$near" : { "$geometry" : { "type" : "Point", "coordinates" : [118.783799, 31.979234] } } } })
    

参考:
https://blog.csdn.net/u014230597/article/details/52635190
https://blog.csdn.net/medea_yang/article/details/53436460