'Geospatial 2dsphere index not creating in MongoDB Atlas and manually

I am trying to create a 2sphere index in my mongodb collection. The index needs to be on location field which is at GeoJSON format:

location: {    
   coordinates: [lat, long],
   type: "Point" 
}

My manual query in JS:

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

When I create the index in Mongo Atlas, it appears and disappears after a few seconds on the screen.

An error is occuring when creating the index but I don't know what.

My $near query:

db.collection(COLLECTION_NAME)
      .find({
        location: {
          $near: {
            $geometry: { type: "Point", coordinates: [lng, lat] },
            $minDistance: 1000,
            $maxDistance: 5000,
          },
        },
      })

Error:

planner returned error :: caused by :: unable to find index for $geoNear query This error is because my index is not creating.

Hope people out there can help! :) Thanks a lot!

Documentation used: https://www.mongodb.com/docs/manual/reference/operator/query/near/



Solution 1:[1]

GeoJSON coords are long,lat not lat,long. It is very likely that you have some bad data in your location field and this is preventing the index from being created correctly. If even one doc in a collection of 1000 has bad geo data, the index will not be created. To test, if you can, drop the data from the collection, create the 2dsphere index, then in a loop add the data back and watch the return code from insert. Bad GeoJSON data will cause an error on insert, allowing you to mark these items as needing attention but permitting the majority to insert with index support.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1