美文网首页
mongodb实现lbs地理位置查找附近的商家

mongodb实现lbs地理位置查找附近的商家

作者: 元宇宙编程 | 来源:发表于2020-12-21 16:52 被阅读0次
1.创建lbs集合存放地点坐标

方式一:

db.lbs.insert(  
   {  
       loc:{  
           type: "Point",  
          coordinates: [113.330611, 23.147234]  
        },  
      name: "林和西"  
    }  
)  

  db.lbs.insert(  
  {  
      loc:{  
          type: "Point",  
          coordinates: [113.328095, 23.165376]  
      },  
      name: "天平架"  
     }  
  )  

方式二:

db.collection.insert({location:[lng,lat],title:'test title'})
2.创建地理位置索引
db.lbs.ensureIndex(  
   {  
        loc: "2dsphere"  
    }  
 )  
3.查询附近的坐标

当前位置为:时代广场,
坐标:113.323568, 23.146436
搜寻附近一公里内的点,由近到远排序

方式一:

db.lbs.find(  
{  
     loc: {  
          $near:{  
              $geometry:{  
                  type: "Point",  
                   coordinates: [113.323568, 23.146436]  
               },  
               $maxDistance: 1000  
             }  
        }  
    }  
 )  

方式二:

db.collection.find(
  {
      location:
      {
          $geoWithin:
          {
              $centerSphere: [ [lng, lat], 检索半径]
          }
      }
   }
)

方式三:

db.collection.find(
{
    location:
    {
        $near:
        [lng, lat]
    }
  }
)

相关文章

网友评论

      本文标题:mongodb实现lbs地理位置查找附近的商家

      本文链接:https://www.haomeiwen.com/subject/ffuovktx.html