Bagikan melalui


$geoWithin (geospasial)

BERLAKU UNTUK: MongoDB vCore

Operator $geoWithin memilih dokumen yang bidang lokasinya sepenuhnya berada dalam geometri tertentu. Operator ini mendukung berbagai operator bentuk termasuk $box, , $polygon, $centerdan $geometry.

Sintaksis

Sintaks untuk $geoWithin operator bervariasi berdasarkan bentuk yang digunakan:

// Using $box
{
  <location field>: {
    $geoWithin: {
      $box: [ [ <bottom left coordinates> ], [ <upper right coordinates> ] ]
    }
  }
}

// Using $center
{
  <location field>: {
    $geoWithin: {
      $center: [ [ <x>, <y> ], <radius> ]
    }
  }
}

// Using $geometry
{
  <location field>: {
    $geoWithin: {
      $geometry: {
        type: <GeoJSON type>,
        coordinates: <coordinates>
      }
    }
  }
}

Parameter-parameternya

Pengaturan Tipe Deskripsi
location field Bidang Bidang yang berisi koordinat lokasi
$box Array Dua set koordinat yang menentukan sudut kotak yang berlawanan
$center Array Koordinat titik tengah dan radius dalam derajat
$geometry Objek Objek GeoJSON yang mendefinisikan batas

Contoh

Pertama, pastikan Anda memiliki indeks 2dsphere:

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

Contoh 1: Menggunakan $box

Temukan toko di area persegi panjang di sekitar toko hiburan rumah:

db.stores.find({
  'location': {
    $geoWithin: {
      $box: [
        [65.0, 65.0],    // Bottom left corner
        [75.0, 75.0]     // Top right corner
      ]
    }
  }
}, {
  name: 1,
  location: 1
})

Kueri ini akan mengembalikan penyimpanan termasuk "Proseware, Inc. | Home Entertainment Hub" (terletak di 70.1272, 69.7296).

Contoh 2: Menggunakan $center

Temukan toko dalam radius melingkar Wide World Importers:

db.stores.find({
  'location': {
    $geoWithin: {
      $center: [
        [-82.5543, -65.105],  // Center point (Wide World Importers location)
        5                     // Radius in degrees
      ]
    }
  }
}, {
  name: 1,
  location: 1
})

Contoh 3: Menggunakan $geometry

Temukan toko dalam area poligon:

db.stores.find({
  'location': {
    $geoWithin: {
      $geometry: {
        type: "Polygon",
        coordinates: [[
          [-85.0, -70.0],
          [-85.0, -60.0],
          [-75.0, -60.0],
          [-75.0, -70.0],
          [-85.0, -70.0]
        ]]
      }
    }
  }
}, {
  name: 1,
  location: 1
})

Untuk menganalisis hasilnya secara lebih menyeluruh:

db.stores.aggregate([
  {
    $match: {
      'location': {
        $geoWithin: {
          $geometry: {
            type: "Polygon",
            coordinates: [[
              [-85.0, -70.0],
              [-85.0, -60.0],
              [-75.0, -60.0],
              [-75.0, -70.0],
              [-85.0, -70.0]
            ]]
          }
        }
      }
    }
  },
  {
    $project: {
      name: 1,
      location: 1,
      _id: 0
    }
  }
])