Master GeoSpatial Queries in MongoDB

Hey Coders! Are you ready to embark on an exciting journey into the world of GeoSpatial queries in MongoDB? Let's dive in and explore everything you need to know to become a GeoSpatial querying expert!

Setting up our playground
 

Creating a GeoSpatial-enabled database

Before we jump into the world of GeoSpatial queries, let's set up our playground. First, we need to create a MongoDB database and collections with GeoSpatial properties. Let's create a database called geoData and two collections: restaurants and parks, each containing a location property representing their GeoSpatial coordinates.

// Creating the geoData database
use geoData
// Creating the restaurants collection with GeoSpatial coordinates
db.createCollection("restaurants", {
  validator: {
    $jsonSchema: {
      bsonType: "object",
      properties: {
        name: { bsonType: "string" },
        location: {
          bsonType: "object",
          properties: {
            type: { bsonType: "string", enum: ["Point"] },
            coordinates: { bsonType: ["array"], items: { bsonType: "number" } }
          },
          required: ["type", "coordinates"]
        }
      },
      required: ["name", "location"]
    }
  }
});
// Creating the parks collection with GeoSpatial coordinates
db.createCollection("parks", {
  validator: {
    $jsonSchema: {
      bsonType: "object",
      properties: {
        name: { bsonType: "string" },
        area: { bsonType: "number" },
        location: {
          bsonType: "object",
          properties: {
            type: { bsonType: "string", enum: ["Point"] },
            coordinates: { bsonType: ["array"], items: { bsonType: "number" } }
          },
          required: ["type", "coordinates"]
        }
      },
      required: ["name", "area", "location"]
    }
  }
});

Now that our database and collections are set up, let's explore various GeoSpatial queries to unleash the power of spatial data!

Exploring GeoSpatial queries finding nearby places
 

1. Finding Nearby Restaurants

Imagine you're hungry and want to find nearby restaurants. Let's use a $nearSphere query to find restaurants within a certain radius of your location.

// Find restaurants within 5 kilometers of your location
db.restaurants.find({
  location: {
    $nearSphere: {
      $geometry: {
        type: "Point",
        coordinates: [yourLongitude, yourLatitude]
      },
      $maxDistance: 5000 // 5 kilometers in meters
    }
  }
});

2. Discovering nearby parks

Now, let's say you're in the mood for a stroll in the park. We can use a similar $nearSphere query to find parks within a certain distance of your location.

// Find parks within 2 kilometers of your location
db.parks.find({
  location: {
    $nearSphere: {
      $geometry: {
        type: "Point",
        coordinates: [yourLongitude, yourLatitude]
      },
      $maxDistance: 2000 // 2 kilometers in meters
    }
  }
});

3. Searching within a Polygonal area

Let's say you're planning a picnic and want to find parks within a specific area defined by a polygon. We can use a $geoWithin query to find parks within the polygonal area.

// Define the polygonal area coordinates
const picnicAreaCoordinates = [
  [lon1, lat1],
  [lon2, lat2],
  [lon3, lat3],
  [lon4, lat4],
  [lon1, lat1] // Closing the polygon
];
// Find parks within the picnic area
db.parks.find({
  location: {
    $geoWithin: {
      $geometry: {
        type: "Polygon",
        coordinates: [picnicAreaCoordinates]
      }
    }
  }
});

4. Finding places along a route

Planning a road trip and need to find rest stops along the route? We can use a $geoIntersects query to find places intersecting with a line representing the route.

// Define the route coordinates
const routeCoordinates = [
  [startLon, startLat],
  [midpointLon, midpointLat],
  [endLon, endLat]
];
// Find rest stops along the route
db.restStops.find({
  location: {
    $geoIntersects: {
      $geometry: {
        type: "LineString",
        coordinates: routeCoordinates
      }
    }
  }
});

Conclusion

Congratulations! You've just scratched the surface of mastering GeoSpatial queries in MongoDB. By understanding the basics, setting up your GeoSpatial playground, and exploring various query examples, you're well on your way to becoming a GeoSpatial querying pro. So, keep experimenting, keep exploring, and let your GeoSpatial adventure unfold!


Similar Articles