$nearSphere(地理空间)

适用对象: MongoDB vCore

$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" })

查找“VanArsdel 图片框架商店”附近的商店(-141.9922,16.8331):

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

示例 2:最大距离

在“Fabrikam Car配件出口”的20 KM内查找商店(-38.4071,-47.2548):

db.stores.find({
  'location': {
    $nearSphere: {
      $geometry: {
        type: "Point",
        coordinates: [-38.4071, -47.2548]
      },
      $maxDistance: 20000  // 20 KM in meters
    }
  }
}, {
  name: 1,
  location: 1
})

示例 3:复杂距离分析

从第四咖啡转盘精品(65.3765,-44.8674)查找和分析 20 到 100 公里之间的商店:

db.stores.aggregate([
  {
    $geoNear: {
      near: {
        type: "Point",
        coordinates: [65.3765, -44.8674]
      },
      distanceField: "sphericalDistance",
      minDistance: 20000,     // 20 KM in meters
      maxDistance: 100000,    // 100 KM in meters
      spherical: true
    }
  },
  {
    $project: {
      name: 1,
      location: 1,
      distanceKm: { $divide: ["$sphericalDistance", 1000] },
      _id: 0
    }
  }
])

$nearSphere以下主要区别$near

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