Solving the MongoDB Error: '$near requires a 2d or 2dsphere index'

intermediate๐Ÿƒ MongoDB2026-06-24| MongoDB 3.6+, Node.js (Mongoose), Python (PyMongo), MongoDB Compass, Linux/macOS/Windows

Error Message

planner returned error :: internal error: $near requires a 2d or 2dsphere index
#mongodb#geospatial#index#2dsphere#mongoose

The Error ScenarioI recently built a 'find nearby coffee shops' feature for a client. Everything looked perfect on paper. I had my GeoJSON objects stored and my $near operator ready to go. But the moment I tested the search against a collection of 50,000 locations, the database threw a punch:

MongoServerError: planner returned error :: internal error: $near requires a 2d or 2dsphere index

Unlike a standard search where MongoDB might settle for a slow collection scan, geospatial queries are different. MongoDB simply refuses to run a $near or $nearSphere query unless it has a specialized index to lean on. It won't even try to guess.

Why MongoDB Demands an IndexCalculating the distance between two points across 10 million documents is incredibly heavy on the CPU. To protect your performance, MongoDB mandates a 2d index for flat Euclidean planes or a 2dsphere index for Earth-like geometry. If you don't have one, the query planner quits immediately rather than risking a database-wide slowdown.

You are likely hitting this wall because:

  • The index was never created on the production database.- The collection was dropped and recreated, wiping out the index.- You are querying the location field, but the index is actually on address.location.- In Mongoose, autoIndex is disabled, so your schema definitions aren't reaching the server.## The 'Right Now' Fix: Using the ShellIf you need to get the app back online immediately, manually create the index using the MongoDB shell (mongosh) or MongoDB Compass. For GeoJSON data stored in a field named location, run this command:
db.places.createIndex({ location: "2dsphere" })

For legacy coordinate pairs like [longitude, latitude], a 2d index works. However, 2dsphere is the gold standard for modern web mapping because it accounts for the Earth's curvature.

Permanent Fix: Automating Indexes in CodeManual fixes are great for emergencies, but your code should handle index creation to keep your Dev, Staging, and Production environments in sync.

1. Using Mongoose (Node.js)In Mongoose, define the index directly within your schema. Make sure your field is typed as a GeoJSON object.

const placeSchema = new mongoose.Schema({
  name: String,
  location: {
    type: {
      type: String,
      enum: ['Point'],
      required: true
    },
    coordinates: {
      type: [Number],
      required: true
    }
  }
});

// Explicitly define the 2dsphere index
placeSchema.index({ location: "2dsphere" });

const Place = mongoose.model('Place', placeSchema);

Pro tip: If you set autoIndex: false in your connection string to improve performance, Mongoose won't build this automatically. You must call await Place.createIndexes() during your app's startup sequence.

2. Using PyMongo (Python)Python developers can ensure the index exists before the first query runs:

from pymongo import MongoClient, GEOSPHERE

client = MongoClient('mongodb://localhost:27017/')
db = client['store_locator']
collection = db['branches']

# This ensures the index exists; it does nothing if it's already there
collection.create_index([("location", GEOSPHERE)])

Using Compound IndexesWhat if you want to find "Sushi restaurants" near a specific point? A simple geospatial index isn't enough for high-traffic apps. You need a compound index. For these to work, the geospatial field must be the first key in the index.

db.places.createIndex({ location: "2dsphere", category: 1 })

This structure allows MongoDB to narrow down the geographic area first before filtering by category.

Verification: Did it Work?Don't take the lack of errors as proof. Verify the index is active by running:

db.places.getIndexes()

Look for the "key": { "location": "2dsphere" } entry. To see it in action, append .explain("executionStats") to your query. If the winningPlan shows a GEO_NEAR_2DSPHERE stage, you are successfully using the index and your query is optimized.

Common Pitfalls- The Longitude-First Rule: MongoDB expects [longitude, latitude]. If you pass [40.7128, -74.0060] (New York City in Lat/Long), the query will fail or return zero results.- Bad Data: If one document has a latitude of 120 (max is 90), index creation will fail with a 'location object expected' error. Clean your data first.- Large Collections: Building an index on 5 million records can lock your database. Use { background: true } to keep your app responsive during the build.

Related Error Notes