Results of my mongoDB $near query are not sorted

316 views Asked by At

When I make a query to my MongoDB database using mongoose and the mongoDB $near geospatial operator (also tried $nearSphere) my code returns a 200 HTTP status with the correct list of documents but they are not sorted from nearest to furthest (which unfortunately defeats the purpose of the $near operator).

I made sure that I have a "2dsphere" index created on my geometry key and that this key is formatted according to the GeoJson guidelines.

This is the code I use to query the database:

const locations = await Location.find({
        geometry: {
            $near: {
                $geometry: {
                    type: 'Point',
                    coordinates: [lon, lat]
                }
            }
        }
    });

Where lat and lon are Floats.

The 3 first objects returned from my app are the following:

{
    "_id": "5e2ef89e326e885327c6e898",
    "address": "20 Brune Street",
    "availability": false,
    "distance_to": 10583,
    "power": 3840,
    "coordinates": {
      "latitude": 51.51792,
      "longitude": -0.075343
    }
  },
  {
    "_id": "5e2ef79d326e885327c6e882",
    "address": "32 Bedford Row",
    "availability": true,
    "distance_to": 8028,
    "power": 3840,
    "coordinates": {
      "latitude": 51.520297,
      "longitude": -0.116327
    }
  },
  {
    "_id": "5e2ef801326e885327c6e891",
    "address": "42 York Way",
    "availability": false,
    "distance_to": 8322,
    "power": 3840,
    "coordinates": {
      "latitude": 51.532265,
      "longitude": -0.12251
    }
  }

Please note that I deliberately do not include the GeoJson key in the returned objects but they are present in each document of the Database.

Am I missing something?

Thanks in advance!

0

There are 0 answers