Geospatial Queries and Indexes in MongoDB (2dsphere, $geoNear)

Table of Contents

  1. Introduction
  2. Understanding Geospatial Data
  3. Types of Geospatial Indexes in MongoDB
  4. The 2dsphere Index Explained
  5. Creating a 2dsphere Index
  6. Storing GeoJSON Data
  7. Geospatial Query Operators
  8. Using $near and $geoWithin
  9. The $geoNear Aggregation Stage
  10. Real-World Use Cases
  11. Best Practices for Geospatial Queries
  12. Conclusion

1. Introduction

Modern applications—from ride-hailing platforms to delivery systems and social networking apps—often depend on location-based data. MongoDB offers robust support for geospatial data through its 2dsphere indexes and a powerful suite of geospatial query operators. This module will walk you through how to store, index, and query location data efficiently in MongoDB.


2. Understanding Geospatial Data

Geospatial data represents geographic locations such as points (latitude and longitude), lines, and polygons. In MongoDB, geospatial data is stored using either legacy coordinate pairs or GeoJSON objects.

GeoJSON is the preferred format for use with 2dsphere indexes and is designed to support Earth’s spherical geometry.

Common GeoJSON Types:

  • Point: A single location
  • LineString: A path or road
  • Polygon: An area like a park or a building outline

3. Types of Geospatial Indexes in MongoDB

MongoDB supports two main types of geospatial indexes:

  • 2d indexes: For flat (Euclidean) geometry; used for legacy applications.
  • 2dsphere indexes: For spherical geometry (Earth-like), ideal for real-world mapping applications.

In this module, we’ll focus on 2dsphere, which is the modern and most widely used option.


4. The 2dsphere Index Explained

A 2dsphere index supports queries that calculate geometries on an earth-like sphere, making it suitable for:

  • Calculating distances between points
  • Determining proximity or bounding areas
  • Filtering documents based on spatial relationships

Use Case Examples:

  • “Find restaurants within 3km of a user”
  • “Locate all warehouses within a delivery zone”

5. Creating a 2dsphere Index

First, insert a document with a GeoJSON point:

jsCopyEditdb.places.insertOne({
  name: "Central Park",
  location: {
    type: "Point",
    coordinates: [-73.9654, 40.7829] // [longitude, latitude]
  }
});

Then create a 2dsphere index on the location field:

jsCopyEditdb.places.createIndex({ location: "2dsphere" });

6. Storing GeoJSON Data

MongoDB supports various GeoJSON formats:

  • Point: { type: "Point", coordinates: [longitude, latitude] }
  • LineString: { type: "LineString", coordinates: [[lng, lat], [lng, lat], ...] }
  • Polygon: Useful for defining zones and boundaries

Example of a polygon:

jsCopyEdit{
  type: "Polygon",
  coordinates: [[
    [-73.97, 40.77],
    [-73.98, 40.78],
    [-73.96, 40.78],
    [-73.97, 40.77]
  ]]
}

7. Geospatial Query Operators

MongoDB provides several operators for querying geospatial data:

  • $near: Returns documents ordered by proximity.
  • $geoWithin: Returns documents located inside a specified geometry.
  • $geoIntersects: Returns documents that intersect with a geometry.

8. Using $near and $geoWithin

$near Example:

jsCopyEditdb.places.find({
  location: {
    $near: {
      $geometry: {
        type: "Point",
        coordinates: [-73.9667, 40.78]
      },
      $maxDistance: 2000 // meters
    }
  }
});

$geoWithin Example:

jsCopyEditdb.places.find({
  location: {
    $geoWithin: {
      $geometry: {
        type: "Polygon",
        coordinates: [[
          [-73.98, 40.76],
          [-73.97, 40.79],
          [-73.95, 40.78],
          [-73.98, 40.76]
        ]]
      }
    }
  }
});

9. The $geoNear Aggregation Stage

$geoNear is used in aggregation pipelines and requires a 2dsphere index.

jsCopyEditdb.places.aggregate([
  {
    $geoNear: {
      near: { type: "Point", coordinates: [-73.9667, 40.78] },
      distanceField: "distance",
      spherical: true,
      maxDistance: 3000
    }
  }
]);

Key Options:

  • near: The central point.
  • distanceField: Field to store the computed distance.
  • spherical: Must be true for 2dsphere.
  • maxDistance/minDistance: Filter by distance in meters.

10. Real-World Use Cases

  • Food Delivery App: Find all restaurants within a delivery radius.
  • Cab Aggregator: Match passengers to nearby drivers in real-time.
  • Retail: Suggest stores near the user.
  • Emergency Services: Dispatch the nearest ambulance or fire truck.
  • Event Planning: Recommend venues near a chosen location.

11. Best Practices for Geospatial Queries

  • Always index the geospatial field with a 2dsphere index.
  • Use GeoJSON format for compatibility and full feature support.
  • Combine geospatial queries with regular filters for more efficient searches.
  • Prefer $geoNear inside aggregation for advanced use cases like sorting and filtering.
  • Be cautious with $near on large datasets—combine with limit to reduce load.

12. Conclusion

MongoDB’s support for geospatial data is powerful and production-ready. By using 2dsphere indexes, GeoJSON formats, and operators like $geoNear and $geoWithin, you can build highly responsive location-based features in your applications.