دوره‌ها / MongoDB / Geospatial Queries (Geospatial Queries)

Geospatial Queries (Geospatial Queries)

15 دقیقه Article

Geospatial Queries: Query های جغرافیایی 🌍

Geospatial Queries برای کار با داده‌های جغرافیایی و مکان‌ها استفاده می‌شوند. MongoDB از GeoJSON و coordinate pairs پشتیبانی می‌کند.

انواع Geospatial Data:

// Point - یک نقطه
{{
  name: "Restaurant",
  location: {{
    type: "Point",
    coordinates: [51.3890, 35.6892]  // [longitude, latitude]
  }}
}}

// Polygon - یک ناحیه
{{
  name: "City",
  boundary: {{
    type: "Polygon",
    coordinates: [[
      [51.0, 35.0],
      [52.0, 35.0],
      [52.0, 36.0],
      [51.0, 36.0],
      [51.0, 35.0]
    ]]
  }}
}}

ساخت Geospatial Index:

// 2dsphere index (برای GeoJSON)
db.places.createIndex({ location: "2dsphere" })

// 2d index (برای coordinate pairs قدیمی)
db.places.createIndex({ location: "2d" })

Query های Geospatial:

// $near - پیدا کردن نزدیک‌ترین مکان‌ها
db.places.find({
  location: {{
    $near: {{
      $geometry: {{
        type: "Point",
        coordinates: [51.3890, 35.6892]  // Tehran
      }},
      $maxDistance: 1000  // 1 کیلومتر
    }}
  }}
})

// $geoWithin - پیدا کردن مکان‌های داخل یک ناحیه
db.places.find({
  location: {{
    $geoWithin: {{
      $geometry: {{
        type: "Polygon",
        coordinates: [[...]]
      }}
    }}
  }}
})

// $geoIntersects - پیدا کردن مکان‌هایی که با geometry تقاطع دارند
db.places.find({
  location: {{
    $geoIntersects: {{
      $geometry: {{
        type: "LineString",
        coordinates: [[...]]
      }}
    }}
  }}
})

مثال عملی:

// Insert مکان‌ها
db.restaurants.insertMany([
  {{
    name: "Restaurant A",
    location: {{ type: "Point", coordinates: [51.3890, 35.6892] }}
  }},
  {{
    name: "Restaurant B",
    location: {{ type: "Point", coordinates: [51.3900, 35.6900] }}
  }}
])

// پیدا کردن رستوران‌های نزدیک به یک نقطه
db.restaurants.find({
  location: {{
    $near: {{
      $geometry: {{ type: "Point", coordinates: [51.3890, 35.6892] }},
      $maxDistance: 500  // 500 متر
    }}
  }}
}).limit(10)
💡 نکته: Geospatial Queries برای اپلیکیشن‌های location-based مثل Uber، Foursquare، و map applications عالی هستند. MongoDB از GeoJSON standard پشتیبانی می‌کند.
✅ یاد گرفتید: Geospatial Queries برای کار با داده‌های جغرافیایی، پیدا کردن مکان‌های نزدیک و query های location-based استفاده می‌شوند!

تمرین‌های عملی

برای تثبیت یادگیری این درس تمرین‌های زیر را حل کنید

تمرین: Geospatial Query Hard
سوال تمرین

🎯 تمرین: جستجوی جغرافیایی

یک geospatial index بسازید و query بنویسید.

پاسخ تمرین
JAVASCRIPT
// Geospatial Index
db.places.createIndex({ location: "2dsphere" })

// $near query
db.places.find({
    location: {
        $near: {
            $geometry: {
                type: "Point",
                coordinates: [51.3890, 35.6892]
            },
            $maxDistance: 1000
        }
    }
})

آماده رفتن به درس بعدی هستید؟

این درس را به پایان رساندید و می‌توانید به درس بعدی بروید.