$nearSphere

$nearSphere 运算符返回具有球体上指定点附近位置字段的文档,并使用球面几何图形计算距离。 运算符比基于地球的 $near计算更准确。

语法

{
  <location field>: {
    $nearSphere: {
      $geometry: {
        type: "Point",
        coordinates: [<longitude>, <latitude>]
      },
      $maxDistance: <distance in meters>,
      $minDistance: <distance in meters>
    }
  }
}

参数

参数 DESCRIPTION
location field 包含 GeoJSON 点的字段
$geometry 指定中心点的 GeoJSON Point 对象
$maxDistance 可选。 球面上的最大距离(以米为单位)
$minDistance 可选。 球面上的最小距离(以米为单位)

例子

为了获得更好的性能,请先创建所需的 2dsphere 索引。

db.stores.createIndex({ "location": "2dsphere" })

该示例使用 $nearSphere 运算符在离球面(类似地球)表面的点(-141.9922、16.83331)最近的存储集合中查找文档。

db.stores.find({
  'location': {
    $nearSphere: {
      $geometry: {
        type: "Point",
        coordinates: [-141.9922, 16.8331]
      }
    }
  }
}, {
  name: 1,
  location: 1
}).limit(2)

查询返回离定义点最远的排序的存储。

  {
    "_id": "643b2756-c22d-4063-9777-0945b9926346",
    "name": "Contoso, Ltd. | Outdoor Furniture Corner - Pagacfort",
    "location": {
      "type": "Point",
      "coordinates": [152.1353, -89.8688]
    }
  },
  {
    "_id": "daa71e60-75d4-4e03-8b45-9df59af0811f",
    "name": "First Up Consultants | Handbag Corner - South Salvatore",
    "location": {
      "type": "Point",
      "coordinates": [150.2305, -89.8431]
    }
  }

示例 2:复杂距离分析

该示例有助于从 Point (65.3765, -44.8674) 查找和分析 200 米到 200 米之间的商店。

db.stores.aggregate([
  {
    $geoNear: {
      near: {
        type: "Point",
        coordinates: [65.3765, -44.8674]
      },
      distanceField: "sphericalDistance",
      minDistance: 20,
      maxDistance: 200,
      spherical: true
    }
  },
  {
    $project: {
      name: 1,
      location: 1,
      distanceKm: { $divide: ["$sphericalDistance", 1000] },
      _id: 0
    }
  },
  {
    $limit: 2
  }
])

查询在“圆环形”搜索区域中搜索 - 查找距离至少20米但距离指定点不超过200米的商店,非常适合“在附近城市查找商店,但不在直接区域查找商店”等方案。

运算符 $nearSphere$near. 之间的主要区别。

  • 前者使用球面几何图形进行距离计算。
  • 前者更准确地用于基于地球的距离计算。
  • 前者更适合需要精确全局距离计算的应用程序