在使用外卖或团购 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]});

   mongodb地图位置排序

   2创建2dsphere 索引

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

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

       db.location.find({

                                       }
                                }
                       }
                  })

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

          db.location.aggregate([

           spherical: true
           }
          }
           ])

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

       db.location.find({

          [
         0,0
         ],
        0.025 //单位为弧度
          ]
      }
       }
        })

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2021-10-24
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2021-08-30
  • 2022-12-23
  • 2022-01-14
相关资源
相似解决方案