0
0
MongodbHow-ToBeginner · 3 min read

How to Create Geospatial Index in MongoDB for Location Queries

To create a geospatial index in MongoDB, use the createIndex() method on a collection with the field and index type, such as { location: '2dsphere' } for GeoJSON data. This index enables efficient queries on location data like points, polygons, and lines.
📐

Syntax

The basic syntax to create a geospatial index in MongoDB is:

  • db.collection.createIndex({ <field>: <indexType> }) - creates an index on the specified field.
  • <field> - the name of the field containing location data.
  • <indexType> - either '2dsphere' for GeoJSON objects or '2d' for legacy coordinate pairs.
mongodb
db.places.createIndex({ location: '2dsphere' })
💻

Example

This example shows how to create a 2dsphere geospatial index on the location field of the places collection. It enables queries like finding documents near a point.

mongodb
use testdb

// Insert sample document with GeoJSON point
 db.places.insertOne({
   name: 'Central Park',
   location: { type: 'Point', coordinates: [-73.9654, 40.7829] }
 })

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

// Query documents near a point
 db.places.find({
   location: {
     $near: {
       $geometry: { type: 'Point', coordinates: [-73.97, 40.77] },
       $maxDistance: 5000
     }
   }
 })
Output
{ "acknowledged" : true, "createdCollectionAutomatically" : false, "numIndexesBefore" : 1, "numIndexesAfter" : 2, "ok" : 1 } { "_id" : ObjectId("..."), "name" : "Central Park", "location" : { "type" : "Point", "coordinates" : [ -73.9654, 40.7829 ] } }
⚠️

Common Pitfalls

Common mistakes when creating geospatial indexes include:

  • Using '2d' index type for GeoJSON data instead of '2dsphere'.
  • Not storing location data in the correct GeoJSON format (type and coordinates).
  • Trying to create multiple geospatial indexes on the same collection which MongoDB does not allow.
  • Forgetting to create the index before running geospatial queries, causing slow performance.
mongodb
/* Wrong: Using '2d' index for GeoJSON data */
db.places.createIndex({ location: '2d' })

/* Right: Use '2dsphere' for GeoJSON */
db.places.createIndex({ location: '2dsphere' })
📊

Quick Reference

Index TypeUse CaseData Format
2dsphereGeoJSON objects (points, polygons){ type: 'Point', coordinates: [lng, lat] }
2dLegacy coordinate pairs[x, y] array of numbers

Key Takeaways

Use createIndex() with '2dsphere' to index GeoJSON location data in MongoDB.
Ensure location data is stored in correct GeoJSON format for geospatial queries.
Avoid using '2d' index type for GeoJSON data; it is for legacy coordinate pairs.
Create geospatial indexes before running location-based queries for better performance.
MongoDB allows only one geospatial index per collection.