$geoIntersects(地理空间运算符)

适用对象: MongoDB vCore

运算符 $geoIntersects 选择其位置字段与指定 GeoJSON 对象相交的文档。 如果要查找与特定地理区域相交的商店,此运算符非常有用。

语法

$geoIntersects 运算符的语法如下所示:

{
  <location field>: {
    $geoIntersects: {
      $geometry: {
        type: <GeoJSON type>,
        coordinates: <coordinates>
      }
    }
  }
}

参数

参数 类型 说明
location field 领域 包含 GeoJSON 对象的字段
type 字符串 GeoJSON 对象类型(例如“Polygon”、“MultiPolygon”)
coordinates 数组 定义 GeoJSON 对象的坐标

示例:

首先,让我们为位置字段创建一个 2dsphere 索引:

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

现在,让我们找到使用集合与特定多边形区域相交的 stores 存储。 此多边形包含数据集中的多个存储位置:

db.stores.find({
  'location': {
    $geoIntersects: {
      $geometry: {
        type: "Polygon",
        coordinates: [[
          [-150.0, 50.0],    // Northwest corner
          [-150.0, 70.0],    // Northeast corner
          [-130.0, 70.0],    // Southeast corner
          [-130.0, 50.0],    // Southwest corner
          [-150.0, 50.0]     // Back to start to close polygon
        ]]
      }
    }
  }
}, {
  name: 1,
  "location": 1
})

此查询返回如下存储:

  • “First Up Consultants |床和巴斯中心 - 南阿米尔“(位于60.7954,-142.0012)

为了演示实际数据点,下面是一个查询,用于查找此区域中的所有存储:

// First, let's see what stores we found
db.stores.aggregate([
  {
    $match: {
      'location': {
        $geoIntersects: {
          $geometry: {
            type: "Polygon",
            coordinates: [[
              [-150.0, 50.0],
              [-150.0, 70.0],
              [-130.0, 70.0],
              [-130.0, 50.0],
              [-150.0, 50.0]
            ]]
          }
        }
      }
    }
  },
  {
    $project: {
      name: 1,
      location: 1,
      _id: 0
    }
  }
])