查询平面上某个点附近的位置

您可以查询出现在平面上指定点附近的位置数据。

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

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

关于此任务

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

在你开始之前

  1. 创建contacts集合:

    db.contacts.insertMany( [
       {
          name: "Evander Otylia",
          phone: "202-555-0193",
          address: [ 55.5, 42.3 ]
       },
       {
          name: "Georgine Lestaw",
          phone: "714-555-0107",
          address: [ -74, 44.74 ]
       }
    ] )
    

    address字段包含旧坐标对。

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

    在字段上创建二维索引address

    db.contacts.createIndex( { address: "2d" } )
    

过程

用于$near查询集合。以下$near查询返回字段在address坐标对 50 米范围内的文档[ -73.92, 40.78 ]

db.contacts.find( {
   address: {
      $near: [ -73.92, 40.78 ],
      $maxDistance : 50
   }
} )

输出:

[
   {
     _id: ObjectId("640a3dd9c639b6f094b00e89"),
     name: 'Georgine Lestaw',
     phone: '714-555-0107',
     address: [ -74, 44.74 ]
   }
]

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

了解更多

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

results matching ""

    No results matching ""