Reputation: 13
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/
Upvotes: 0
Views: 1100
Reputation: 7578
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.
Upvotes: 1