codingstuff.io
ExploreTutorialsProblemsCS Subjects
Get Started
ExploreTutorialsProblemsCS Subjects
Get Started
codingstuff.io

Master the art of building software through interactive tutorials, real-world problems, and guided projects.

Pune, Maharashtra, India

codingstuffmail@gmail.com

Product

  • Explore
  • Tutorials
  • Problems
  • CS Subjects

Company

  • About
  • Contact
  • Privacy Policy
  • Terms & Conditions
  • Sitemap

© 2026 codingstuff.io. All rights reserved.

Built with ❤️ for developers everywhere

/
/
All Tutorials
🍃

MongoDB

23 / 65 topics
19Indexing Basics20Creating Indexes21Compound Indexes22Unique Indexes23Geospatial Indexes24Explain Command
Tutorials/MongoDB/Geospatial Indexes
🍃MongoDB

Geospatial Indexes

Updated 2026-04-20
3 min read

Geospatial Indexes

Introduction

Geospatial data is becoming increasingly important as applications need to handle location-based queries efficiently. MongoDB provides robust support for geospatial indexing, allowing developers to perform complex spatial operations such as finding nearby locations, calculating distances, and more. In this section, we will explore how to create and use geospatial indexes in MongoDB.

Understanding Geospatial Data

Geospatial data typically represents points on the Earth's surface using coordinates (latitude and longitude). MongoDB supports two types of geospatial data:

  1. Point: Represents a single location.
  2. Polygon: Represents an area defined by multiple points.

MongoDB uses GeoJSON format to store geospatial data, which is a standard for encoding various geographic data structures.

Creating Geospatial Indexes

To perform geospatial queries efficiently, you need to create the appropriate index on your collection. MongoDB supports two types of geospatial indexes:

  1. 2dsphere: Used for storing and querying geospatial data that represents points or polygons on a sphere (e.g., Earth).
  2. 2d: Used for storing and querying geospatial data that is limited to a single plane, such as a map.

Creating a 2dsphere Index

To create a 2dsphere index, use the createIndex method with the 2dsphere option. Here's an example:

db.collection.createIndex({ location: "2dsphere" });

In this example, location is the field that stores geospatial data in GeoJSON format.

Creating a 2d Index

To create a 2d index, use the createIndex method with the 2d option. This index is suitable for planar (flat) coordinates:

db.collection.createIndex({ location: "2d" });

Performing Geospatial Queries

Once you have created a geospatial index, you can perform various queries to find documents based on their spatial relationship.

Finding Documents Within a Radius

To find documents within a certain radius of a point, use the $near operator. Here's an example:

db.collection.find({
  location: {
    $near: {
      $geometry: {
        type: "Point",
        coordinates: [-73.935242, 40.73061]
      },
      $maxDistance: 1000 // in meters
    }
  }
});

This query finds all documents within a 1000-meter radius of the specified point.

Finding Documents Within a Polygon

To find documents within a polygon, use the $geoWithin operator. Here's an example:

db.collection.find({
  location: {
    $geoWithin: {
      $geometry: {
        type: "Polygon",
        coordinates: [
          [ [-73.95, 40.8], [-73.95, 40.7], [-73.9, 40.7], [-73.9, 40.8] ]
        ]
      }
    }
  }
});

This query finds all documents within the specified polygon.

Calculating Distance

To calculate the distance between two points, use the $geoNear aggregation stage. Here's an example:

db.collection.aggregate([
  {
    $geoNear: {
      near: { type: "Point", coordinates: [-73.935242, 40.73061] },
      distanceField: "distance",
      spherical: true
    }
  }
]);

This aggregation calculates the distance from each document to the specified point and stores it in a new field called distance.

Best Practices

  1. Choose the Right Index Type: Use 2dsphere for global data and 2d for planar coordinates.
  2. Index Only Relevant Fields: Only index fields that are frequently used in geospatial queries to optimize performance.
  3. Use GeoJSON Format: Ensure that your geospatial data is stored in the correct GeoJSON format.
  4. Limit Results: Use $limit to restrict the number of results returned by a query, especially for large datasets.
  5. Monitor Performance: Regularly monitor query performance and adjust indexes as needed.

Conclusion

Geospatial indexing in MongoDB is a powerful feature that enables efficient querying of location-based data. By understanding how to create and use geospatial indexes, you can build applications that handle complex spatial queries with ease. Always consider the specific requirements of your application when designing your database schema and choosing index types.


PreviousUnique IndexesNext Explain Command

Recommended Gear

Unique IndexesExplain Command