$geometry(地理空间)

适用对象: MongoDB vCore

$geometry 运算符指定地理空间查询的 GeoJSON 几何对象。 它用于其他地理空间运算符来定义空间计算的形状和点。

语法

{
  $geometry: {
    type: <GeoJSON type>,
    coordinates: <coordinates>
  }
}

参数

参数 类型 DESCRIPTION
type 字符串 GeoJSON 对象类型(Point、Polygon、MultiPolygon 等)
coordinates 数组 定义 GeoJSON 对象的坐标

例子

创建所需的 2dsphere 索引:

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

示例 1:点几何图形

查找第一 Up 顾问手表市场附近的商店 (46.2917, -62.6354):

db.stores.find({
  'location': {
    $near: {
      $geometry: {
        type: "Point",
        coordinates: [46.2917, -62.6354]
      }
    }
  }
}, {
  name: 1,
  location: 1
})

示例 2:多边形几何图形

在 Wide World Importers Headphone Corner 的多边形内查找商店(-82.5543、-65.105):

db.stores.find({
  'location': {
    $geoWithin: {
      $geometry: {
        type: "Polygon",
        coordinates: [[
          [-85.0, -67.0],
          [-85.0, -63.0],
          [-80.0, -63.0],
          [-80.0, -67.0],
          [-85.0, -67.0]  // Close the polygon
        ]]
      }
    }
  }
}, {
  name: 1,
  location: 1
})

示例 3:MultiPolygon Geometry

查找多个区域中的存储:

db.stores.find({
  'location': {
    $geoWithin: {
      $geometry: {
        type: "MultiPolygon",
        coordinates: [
          [[ // First polygon (around Northwind Traders)
            [120.0, -13.0],
            [120.0, -10.0],
            [125.0, -10.0],
            [125.0, -13.0],
            [120.0, -13.0]
          ]],
          [[ // Second polygon (around First Up Consultants)
            [44.0, -64.0],
            [44.0, -61.0],
            [48.0, -61.0],
            [48.0, -64.0],
            [44.0, -64.0]
          ]]
        ]
      }
    }
  }
}, {
  name: 1,
  location: 1
})