Assignments Of Day 16: MongoDB Geospatial Indexing

Rashmi Mishra
0

 

Assignments Of Day 16: MongoDB Geospatial Indexing

Assignment 1: Create a Collection with GeoJSON Data

Objective: Create a collection named locations and insert multiple documents with GeoJSON data for various places (e.g., restaurants, landmarks, cities).

Step-by-Step Solution:

1.  Create a new collection called locations.

2.  Insert documents containing GeoJSON Point data with latitude and longitude coordinates for several places.

Example Code:
javascript
db.locations.insertMany([
  {
    name: "Central Park",
    location: {
      type: "Point",
      coordinates: [-73.9654, 40.7829]  // Coordinates for Central Park, NYC
    }
  },
  {
    name: "Statue of Liberty",
    location: {
      type: "Point",
      coordinates: [-74.0445, 40.6892]  // Coordinates for Statue of Liberty
    }
  },
  {
    name: "Times Square",
    location: {
      type: "Point",
      coordinates: [-73.9857, 40.7580]  // Coordinates for Times Square
    }
  }
])

Explanation:

  • GeoJSON Format: In MongoDB, GeoJSON is used to represent geographical data. A Point type stores a pair of latitude and longitude.
  • Inserting Documents: The documents are inserted using insertMany and each document has a location field storing the GeoJSON Point.

Assignment 2: Create a 2dsphere Index

Objective: Create a 2dsphere index on the location field to enable geospatial queries.

Step-by-Step Solution:

1.  Create a 2dsphere index on the location field of the locations collection.

Example Code:
javascript
db.locations.createIndex({ location: "2dsphere" })

Explanation:

  • 2dsphere Index: This type of index is required to perform geospatial queries such as finding nearby locations or querying within a specific radius.

Assignment 3: Query Locations Within a Radius Using $geoWithin

Objective: Write a query to find all locations within a 1-kilometer radius of a given point.

Step-by-Step Solution:

1.  Find all locations within a 1 km radius of Central Park.

2.  Use $geoWithin with $centerSphere to specify the radius in radians.

Example Code:
javascript
db.locations.find({
  location: {
    $geoWithin: {
      $centerSphere: [
        [-73.9654, 40.7829],  // Central Park coordinates
        1 / 3963.2            // Radius in radians (1 kilometer)
      ]
    }
  }
})

Explanation:

  • The radius is given in radians. To convert kilometers to radians, divide the distance by 3963.2 (the Earth's radius in kilometers).
  • $geoWithin ensures that the query returns locations within the specified radius.

Assignment 4: Find Locations Within a Polygon Using $geoWithin

Objective: Query all locations within a polygon defined by several points.

Step-by-Step Solution:

1.  Define a polygon with multiple points.

2.  Use $geoWithin with a Polygon to find all locations within this polygon.

Example Code:
javascript
db.locations.find({
  location: {
    $geoWithin: {
      $geometry: {
        type: "Polygon",
        coordinates: [
          [
            [-73.9740, 40.7850],
            [-73.9620, 40.7850],
            [-73.9620, 40.7980],
            [-73.9740, 40.7980],
            [-73.9740, 40.7850]
          ]
        ]
      }
    }
  }
})

Explanation:

  • Polygon: A polygon is defined by a set of coordinates. The query finds all locations within the boundaries of the polygon.
  • $geoWithin with a Polygon allows us to filter locations based on geographic boundaries.

Assignment 5: Find the Nearest Locations Using $near

Objective: Use the $near operator to find the closest locations to a given point.

Step-by-Step Solution:

1.  Use the $near operator to find locations closest to the Statue of Liberty.

2.  Specify a maximum distance for the search.

Example Code:
javascript
db.locations.find({
  location: {
    $near: {
      $geometry: {
        type: "Point",
        coordinates: [-74.0445, 40.6892]  // Statue of Liberty coordinates
      },
      $maxDistance: 2000  // Maximum distance in meters (2 kilometers)
    }
  }
})

Explanation:

  • $near finds the closest documents to a given point.
  • The $maxDistance option limits the search to a specified distance in meters.

Assignment 6: Find Locations Using $nearSphere

Objective: Use the $nearSphere operator to find locations within a spherical range.

Step-by-Step Solution:

1.  Use $nearSphere to find locations within 5 kilometers of Times Square.

Example Code:
javascript
db.locations.find({
  location: {
    $nearSphere: {
      $geometry: {
        type: "Point",
        coordinates: [-73.9857, 40.7580]  // Times Square coordinates
      },
      $maxDistance: 5000  // 5 kilometers
    }
  }
})

Explanation:

  • $nearSphere is similar to $near, but it uses a spherical model (not planar geometry) to calculate distances, which is more accurate for geospatial queries.
  • The $maxDistance is in meters, so 5000 meters equals 5 kilometers.

Assignment 7: Use $centerSphere for Radius Queries

Objective: Query locations within a radius using $centerSphere operator.

Step-by-Step Solution:

1.  Query all locations within a 3-kilometer radius of the Statue of Liberty using $centerSphere.

Example Code:
javascript
db.locations.find({
  location: {
    $geoWithin: {
      $centerSphere: [
        [-74.0445, 40.6892],  // Statue of Liberty coordinates
        3 / 3963.2            // Radius in radians (3 kilometers)
      ]
    }
  }
})

Explanation:

  • $centerSphere is used to find documents within a circular region defined by a center point and a radius. The radius is given in radians.

Assignment 8: Add More Locations and Test Queries

Objective: Insert additional documents and test the queries with the new data.

Step-by-Step Solution:

1.  Insert additional locations into the locations collection.

2.  Run the geospatial queries from previous assignments to verify results with new data.

Example Code:
javascript
db.locations.insertMany([
  {
    name: "Brooklyn Bridge",
    location: {
      type: "Point",
      coordinates: [-73.9969, 40.7061]  // Coordinates for Brooklyn Bridge
    }
  },
  {
    name: "Empire State Building",
    location: {
      type: "Point",
      coordinates: [-73.9857, 40.7484]  // Coordinates for Empire State Building
    }
  }
])
 
// Running a query to find all locations within a 2 km radius of the Empire State Building:
db.locations.find({
  location: {
    $geoWithin: {
      $centerSphere: [
        [-73.9857, 40.7484],  // Empire State Building coordinates
        2 / 3963.2            // Radius in radians (2 kilometers)
      ]
    }
  }
})

Explanation:

  • Inserting new locations helps verify the functionality of geospatial queries across different types of places.
  • Test the queries with the newly inserted data to ensure the geospatial queries work correctly.

Assignment 9: Query Locations Using $geoIntersects

Objective: Query locations that intersect with a given GeoJSON shape (e.g., a circle or polygon).

Step-by-Step Solution:

1.  Use $geoIntersects with a GeoJSON shape (circle or polygon).

2.  Query locations that intersect with the defined shape.

Example Code:
javascript
db.locations.find({
  location: {
    $geoIntersects: {
      $geometry: {
        type: "Polygon",
        coordinates: [
          [
            [-73.9857, 40.7484],  // Coordinates for the polygon
            [-73.9820, 40.7484],
            [-73.9820, 40.7510],
            [-73.9857, 40.7510],
            [-73.9857, 40.7484]
          ]
        ]
      }
    }
  }
})

Explanation:

  • $geoIntersects finds documents where the specified geometry intersects with the given shape.
  • This operator is useful for complex geospatial queries involving areas defined by shapes like polygons.

Assignment 10: Optimize Performance with Geospatial Queries

Objective: Learn how to optimize geospatial queries by ensuring proper indexing and query design.

Step-by-Step Solution:

1.  Ensure proper 2dsphere index is present.

2.  Run a geospatial query and analyze the query execution plan using explain().

Example Code:
javascript
db.locations.createIndex({ location: "2dsphere" })
 
// Running a geospatial query and checking the execution plan
db.locations.find({
  location: {
    $nearSphere: {
      $geometry: {
        type: "Point",
        coordinates: [-73.9857, 40.7484]  // Empire State Building coordinates
      },
      $maxDistance: 5000  // 5 kilometers
    }
  }
}).explain("executionStats")

Explanation:

  • Running explain("executionStats") helps analyze how the query is executed and whether it's utilizing the appropriate index.
  • Ensuring a 2dsphere index is present is essential for performance, especially when dealing with large datasets.

These assignments cover the basics and advanced use cases of MongoDB geospatial indexing. Each assignment builds on the previous one, allowing students to gain hands-on experience with querying, inserting, and indexing geospatial data in MongoDB.

Post a Comment

0Comments

Post a Comment (0)

About Me