$geometry

$geometry 연산자는 지리 공간적 쿼리에 대한 GeoJSON 기하 개체를 지정합니다. 다른 지리 공간적 연산자 내에서 공간 계산을 위한 모양과 점을 정의하는 데 사용됩니다.

문법

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

매개 변수

매개 변수 Description
type GeoJSON 개체 유형(점, 다각형, 다중 다각형 등)
coordinates GeoJSON 개체를 배열로 정의하는 좌표

예시

stores 데이터 세트의 샘플 json을 통해 사용법을 이해해 보겠습니다.

{
    "_id": "0fcc0bf0-ed18-4ab8-b558-9848e18058f4",
    "name": "First Up Consultants | Beverage Shop - Satterfieldmouth",
    "location": {
        "lat": -89.2384,
        "lon": -46.4012
    },
    "staff": {
        "totalStaff": {
            "fullTime": 8,
            "partTime": 20
        }
    },
    "sales": {
        "totalSales": 75670,
        "salesByCategory": [
            {
                "categoryName": "Wine Accessories",
                "totalSales": 34440
            },
            {
                "categoryName": "Bitters",
                "totalSales": 39496
            },
            {
                "categoryName": "Rum",
                "totalSales": 1734
            }
        ]
    },
    "promotionEvents": [
        {
            "eventName": "Unbeatable Bargain Bash",
            "promotionalDates": {
                "startDate": {
                    "Year": 2024,
                    "Month": 6,
                    "Day": 23
                },
                "endDate": {
                    "Year": 2024,
                    "Month": 7,
                    "Day": 2
                }
            },
            "discounts": [
                {
                    "categoryName": "Whiskey",
                    "discountPercentage": 7
                },
                {
                    "categoryName": "Bitters",
                    "discountPercentage": 15
                },
                {
                    "categoryName": "Brandy",
                    "discountPercentage": 8
                },
                {
                    "categoryName": "Sports Drinks",
                    "discountPercentage": 22
                },
                {
                    "categoryName": "Vodka",
                    "discountPercentage": 19
                }
            ]
        },
        {
            "eventName": "Steal of a Deal Days",
            "promotionalDates": {
                "startDate": {
                    "Year": 2024,
                    "Month": 9,
                    "Day": 21
                },
                "endDate": {
                    "Year": 2024,
                    "Month": 9,
                    "Day": 29
                }
            },
            "discounts": [
                {
                    "categoryName": "Organic Wine",
                    "discountPercentage": 19
                },
                {
                    "categoryName": "White Wine",
                    "discountPercentage": 20
                },
                {
                    "categoryName": "Sparkling Wine",
                    "discountPercentage": 19
                },
                {
                    "categoryName": "Whiskey",
                    "discountPercentage": 17
                },
                {
                    "categoryName": "Vodka",
                    "discountPercentage": 23
                }
            ]
        }
    ]
}

예제 1: 기하 도형을 가리키는 가장 가까운 저장소 찾기

성능을 향상시키려면 필요한 2dsphere 인덱스 만들기부터 시작합니다.

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

쿼리는 좌표 [46.2917, -62.6354]의 지점에 가장 가까운 최대 두 개의 저장소를 검색합니다. $near 연산자를 사용하여 특정 지점에서 거리를 기준으로 결과를 정렬하여 지정된 위치에 지리적으로 가장 가까운 저장소를 찾을 수 있습니다.

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

이 쿼리에서 반환된 처음 두 가지 결과는 다음과 같습니다.

[
  {
    "_id": "59c355e9-586c-44f8-bbaf-a87989142119",
    "name": "Relecloud | Outdoor Furniture Shop - Chetside",
    "location": { "lat": 46.188, "lon": -62.2789 }
  },
  {
    "_id": "d3a9cc23-e6ae-4806-93ac-1ade2f624742",
    "name": "VanArsdel, Ltd. | Furniture Place - North Dustinside",
    "location": { "lat": 47.3426, "lon": -62.4031 }
  }
]

예제 2: 다각형 기하 도형에 가장 가까운 저장소 찾기

이 쿼리는 위치가 [-80.0, -75.0]에서 [-55.0, -70.0]까지 좌표로 제한된 정의된 사각형 다각형과 교차하는 최대 2개의 저장소를 찾습니다.

$geoIntersects 연산자는 다각형 경계와 겹치거나 닿는 저장소를 찾습니다. 이는 특정 지리적 영역과 상호 작용하는 위치를 식별하는 데 적합합니다. 해당 위치가 완전히 다각형 경계 안에 있는지 아니면 경계를 넘었는지 여부는 중요하지 않습니다.

db.stores.find({
  location: {
    $geoIntersects: {
      $geometry: {
        type: "Polygon",
        coordinates: [[
          [-80.0, -75.0],   // Bottom-left
          [-80.0, -70.0],   // Top-left
          [-55.0, -70.0],   // Top-right
          [-55.0, -75.0],   // Bottom-right
          [-80.0, -75.0]    // Close polygon
        ]]
      }
    }
  }
}, {
  name: 1,
  location: 1,
  city: 1
}).limit(2)

이 쿼리에서 반환된 처음 두 결과입니다.

[
  {
    "_id": "6bba7117-d180-4584-b50c-a2f843e9c9ab",
    "name": "Wide World Importers | Craft Supply Mart - Heaneybury",
    "location": { "lat": -64.4843, "lon": -107.7003 },
    "city": "Heaneybury"
  },
  {
    "_id": "2fd37663-e0ff-41d0-9c5a-3aec86285daa",
    "name": "Relecloud | Cleaning Supply Closet - Patiencehaven",
    "location": { "lat": -70.6077, "lon": -105.9901 },
    "city": "Patiencehaven"
  }
]

예제 3: 다중 다각형 기하 도형에 가장 가까운 저장소 찾기

이 예제에서는 위치가 정의된 두 사각형 영역(MultiPolygon) 중 하나에 속하는 최대 두 개의 저장소를 검색합니다. 하나는 좌표 [120.0, -13.0]에서 [125.0, -10.0]에, 다른 하나는 [44.0, -64.0]에서 [48.0, -61.0]에 가깝습니다.

MultiPolygon 기하 도형이 있는 $geoWithin 연산자를 사용하여 지정된 다각형으로 묶인 저장소를 검색하므로 인접하지 않은 여러 지리적 영역에서 동시에 쿼리하는 데 유용합니다.

db.stores.find({
  location: {
    $geoWithin: {
      $geometry: {
        type: "MultiPolygon",
        coordinates: [
          [[
            [120.0, -13.0],
            [120.0, -10.0],
            [125.0, -10.0],
            [125.0, -13.0],
            [120.0, -13.0]
          ]],
          [[
            [44.0, -64.0],
            [44.0, -61.0],
            [48.0, -61.0],
            [48.0, -64.0],
            [44.0, -64.0]
          ]]
        ]
      }
    }
  }
}, {
  name: 1,
  location: 1
}).limit(2)

이 쿼리에서 반환된 처음 두 가지 결과는 다음과 같습니다.

[
  {
    "_id": "6d70de9c-7b83-426d-81aa-f2173f97b64d",
    "name": "Fabrikam, Inc. | Footwear Haven - Port Erling",
    "location": { "lat": 45.641, "lon": -118.4963 }
  },
  {
    "_id": "96d48224-ce10-4a61-999a-8536d442f81a",
    "name": "Wide World Importers | Eyewear Bazaar - West Oletachester",
    "location": { "lat": 47.3461, "lon": -61.6605 }
  }
]