Skip to main content

Geospatial indexes

Geospatial indexing in MongoDB allows you to perform queries on geometric data types like points, lines, and polygons. These indexes are particularly useful for location-based services such as mapping, routing, and geofencing. MongoDB supports two main types of geospatial indexes: 2d indexes and 2dsphere indexes.

2d Index

The 2d index is suitable for data that lies in a two-dimensional plane. It's generally used for legacy coordinate pairs.

// Create a 2d index on the "loc" field
db.places.createIndex({ "loc": "2d" })

2dsphere Index

The 2dsphere index is used for data that is based on a sphere (like Earth). It supports more complex geometries like points, lines, and polygons.

// Create a 2dsphere index on the "location" field
db.places.createIndex({ "location": "2dsphere" })

Features of Geospatial Indexes

  1. Near Queries: Find documents near a specific point.

    // Find places within 1000 meters of a point
    db.places.find({
    "location": {
    "$near": {
    "$geometry": { "type": "Point", "coordinates": [40, -70] },
    "$maxDistance": 1000
    }
    }
    })
  2. Within Queries: Find documents within a specific geometry (e.g., polygon).

    // Find places within a polygon
    db.places.find({
    "location": {
    "$geoWithin": {
    "$geometry": {
    "type": "Polygon",
    "coordinates": [[[0, 0], [3, 6], [6, 1], [0, 0]]]
    }
    }
    }
    })
  3. Intersect Queries: Find geometries that intersect with a given geometry.

    // Find lines intersecting a given point
    db.lines.find({
    "path": {
    "$geoIntersects": {
    "$geometry": { "type": "Point", "coordinates": [2, 2] }
    }
    }
    })
  4. Bounding Box Queries: Find documents within a bounding box.

    // Find places within a bounding box
    db.places.find({
    "location": {
    "$geoWithin": {
    "$box": [[0, 0], [5, 5]]
    }
    }
    })
  5. Geohaystack Index: This is a special type of index optimized for very fast bounding box queries. However, it's less flexible than the other types.

Considerations and Limitations

  1. Complexity: Geospatial queries can be computationally intensive, especially for complex geometries.

  2. Spherical and Planar Geometry: The 2dsphere index assumes a spherical model of the Earth, while the 2d index assumes a flat, two-dimensional plane. Choose the index type based on your specific use-case.

  3. Multiple Fields: You can have multiple geospatial indexes on a collection, but a single query can only use one of them.

  4. Index Size: Geospatial indexes can consume a significant amount of memory, especially for large datasets with complex geometries.