查询球体上某个点附近的位置

您可以查询球体上指定点附近出现的位置数据。

要查询指定点附近的位置数据,请使用 $near运算符:

db.<collection>.find( {
   <location field> : {
      $near : {
         $geometry : {
            type : "Point",
            coordinates : [ <longitude>, <latitude> ]
         },
         $maxDistance : <distance in meters>
      }
    }
 } )

关于此任务

  • 当您指定经度和纬度坐标时,请先列出 经度,然后列出纬度
    • 有效的经度值介于-180和之间180(包含两者)。
    • 有效的纬度值介于-90和之间90(包含两者)。
  • 指定字段中的距离(以$maxDistance为单位) 。

在你开始之前

  1. 创建一个places包含这些文档的集合:

    db.places.insertMany( [
       {
          loc: { type: "Point", coordinates: [ -73.97, 40.77 ] },
          name: "Central Park",
          category : "Park"
       },
       {
          loc: { type: "Point", coordinates: [ -73.88, 40.78 ] },
          name: "La Guardia Airport",
          category: "Airport"
       },
       {
          loc: { type: "Point", coordinates: [ -1.83, 51.18 ] },
          name: "Stonehenge",
          category : "Monument"
       }
    ] )
    

    该字段中的值locGeoJSON 点。

  2. 要使用运算符查询位置数据,您必须在包含位置数据的字段上$near创建地理空间索引。

    在字段上创建 2dsphere 索引loc

    db.places.createIndex( { "loc": "2dsphere" } )
    

过程

用于$near查询集合。以下$near查询返回包含loc位于 的 GeoJSON 点 5000 米范围内的字段的文档[ -73.92, 40.78 ]

db.places.find( {
   loc: {
      $near: {
         $geometry: {
            type: "Point",
            coordinates: [ -73.92, 40.78 ]
         },
         $maxDistance : 5000
      }
   }
} )

输出:

[
  {
    _id: ObjectId("63f7c3b15e5eefbdfef81cab"),
    loc: { type: 'Point', coordinates: [ -73.88, 40.78 ] },
    name: 'La Guardia Airport',
    category: 'Airport'
  },
  {
    _id: ObjectId("63f7c3b15e5eefbdfef81caa"),
    loc: { type: 'Point', coordinates: [ -73.97, 40.77 ] },
    name: 'Central Park',
    category: 'Park'
  }
]

结果按照距查询点的距离从最近到最远排序。

了解更多

Copyright © 上海锦木信息技术有限公司 all right reserved,powered by Gitbook文件修订时间: 2023-09-01 17:10:26

results matching ""

    No results matching ""