$near

运算符 $near 返回其位置字段接近指定点(按距离排序)的文档。 它需要“2dsphere”索引,并返回最接近到最远的文档。

语法

{
  <location field>: {
    $near: {
      $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" })

例子

该示例演示如何使用地理空间搜索查找与特定地理点(70.1272,69.7296)最近的两个存储区。

db.stores.find({
  'location': {
    $near: {
      $geometry: {
        type: "Point",
        coordinates: [69.7296, 70.1272]  // [longitude, latitude]
      }
    }
  }
}, {
  name: 1,
  location: 1
}).limit(2)

查询在存储集合中搜索离给定点最近的位置,并按距离的升序返回它们。 它用于在商店定位符或送货服务等应用程序中“查找最近的位置”功能。

{
   "_id": "3882eb86-5dd6-4701-9640-f670ccb67859",
   "name": "Fourth Coffee | DJ Equipment Stop - Schuppestad",
   "location": { "lat": 69.4923, "lon": 70.1851 }
 },
 {
   "_id": "bbec6d3e-1666-45b4-8803-8b7ef8544845",
   "name": "First Up Consultants | Baby Products Bargains - South Keenan",
   "location": { "lat": 69.2158, "lon": 70.3328 }
 }

示例 2:同时使用最小距离和最大距离

聚合查询查找特定距离范围内的存储点 [70.3328, 69.2158] 并计算其距离(以公里为单位)。

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

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