Hi @Neophyte, thanks for the additional context!
I see you have both a 2d and 2dsphere on your location data, is there a reason why?
Usually, 2d indexes are needed if you are dealing with plane geometry or using legacy coordinate pairs like so:
location: [ <longitude>, <latitude> ]
Data stored in this format needs to be queried like so:
{ location : { $near : [ <longitude>, <latitude> ], $maxDistance: , <maxDistanceInRadians> } }
On the other hand, a 2dsphere index, expects the data to be stored as one of the GeoJSON object types.
I’d actually recommend using the 2dsphere index as you’re dealing with spherical geometry (e.g. finding nearest cities).
Also, queries need to specify longitude first and then latitude .
So there are two things to try, but first do these two steps, no matter which option you choose:
- Drop both of your geospatial indexes.
- Modify your
coordinatesvariable to list longitude first, then latitude
OPTION 1: If keeping your legacy coordinate pairs:
- Only recreate your
2dindex - Remove this entire section:
and replace with this:
string query = $@"{ Localizacao: { $near: {coordinates}, $maxDistance: 100000 }";
As you can see, your query needed to remove the $geometry operator and match the field name you created the index on.
Try running the query and see if it returns what you’re expecting (note you may have to adjust the maxDistance you input in this query format as it expects Radians).
OR
OPTION 2: If changing your data to GeoJSON format (recommended):
- Update your data to be in proper GeoJSON Point object type.
- Only recreate the
2dsphereindex on your newly formed GeoJSON objects. - Modify your existing query to match your actual field name that has the
2dsphereindex:
string query = "{ Localizacao: { $near: { $geometry: { type: \"Point\",";
Try running the query and see if what you expect returns.
Let me know how this goes and feel free to ask any questions if you need me to clarify anything here. ![]()