mongodb地图位置排序

在使用外卖或团购 App 筛选商家时,我们经常会用到一个功能,叫作按照离我最近排序。在使用共享单车时,App 会自动帮我们搜索出,距离我们最近几公里内的单车。那么这两种场景,在服务端要如何实现呢?今天我们将使用 mongodb 来实现这两种场景。

1.按照离我最近排序

   1、创建一个 location 库,然后插入一些数据

    db.location.insert({"lng":经度,"lat":纬度,"loc":[lng,lat]});

    db.location.insert({"lng":1,"lat":1,"loc":[1,1]});

    db.location.insert({"lng":2,"lat":2,"loc":[2,2]});

   db.location.insert({"lng":3,"lat":3,"loc":[3,3]});
   db.location.insert({"lng":-1,"lat":-1,"loc":[-1,-1]});
   db.location.insert({"lng":-2,"lat":-2,"loc":[-2,2]});
 
 db.location.insert({"lng":-3,"lat":-3,"loc":[-3,-3]});

   

   2创建2dsphere 索引

         db.location.ensureIndex({"loc":"2dsphere"})

   3、索引加好后,我们就可以来实现按照离我最近排序了

       db.location.find({

              "loc":{
               "$nearSphere":{
                   "$geometry":{
                      "type":"Point",
                         "coordinates":[0,0]
                                       }
                                }
                       }
                  })

    4、按照离我最近排序,除了使用 $nearSphere 查询外,我们还可以使用 aggregate 来实现。

          db.location.aggregate([

           {
            $geoNear: {
            near: { type: "Point", coordinates: [ 0 , 0 ] },
           distanceField: "distance",
           spherical: true
           }
          }
           ])

2、距离我们最近几公里内的单车

       db.location.find({

          "loc":{
           "$geoWithin":{
           "$centerSphere":[
          [
         0,0
         ],
        0.025 //单位为弧度
          ]
      }
       }
        })

posted @ 2019-03-28 14:11  平平淡淡的小黑  阅读(755)  评论(0编辑  收藏  举报