Search code examples
laravelmongodbaggregation-frameworkgeo

geoNear pulling inacurate results in MongoDB


In my DB there are comments, each comment has each country Long Lat, but MongoDB giving a result that is inaccurate, i.e I'm providing Brazil [Lon Lat] as Input in query

 db.posts.aggregate([ { "$geoNear": {

         "near": [-69.7145414,-13.6574511 ],
         "spherical": true,
         "distanceField": "distance",
         "num":1000000,
        "query":{"post_id":"5efc430e25a363375860e842",}
     }},
     {
        "$sort":{"distance":1}
     } ])

What I'm getting a result is

  1. Bolivia (409.5 km far from Brazil)
  2. Paraguay (1293 km far from Brazil)
  3. Peru (1645 km far from Brazil)
  4. Guyana (1188 km far from Brazil)

you can see that

  • Result 4 is near rather than result 2, so it should be at position 2 This is how I'm getting inaccurate result.

Distance calculated using this website: https://www.movable-type.co.uk/scripts/latlong.html

Longitude Latitude That I'm using are as follows

"Bolivia" => [
    "latitude" => -16.0705819,
    "longitude" => -72.5931926
],
"Paraguay" => [
    "latitude" => -23.3601858,
    "longitude" => -62.9462413
],
"Peru" => [
    "latitude" => -9.1084506,
    "longitude" => -84.0750546
],
"Guyana" => [
    "latitude" => 4.9392707,
    "longitude" => -63.4541328
],
"Brazil" => [
    "latitude" => -13.6574511,
    "longitude" => -69.7145414
]

These Latitude/Longitude get using with this link: https://www.google.com/maps/place/Brazil/@-13.6574511,-69.7145414,4z/data=!3m1!4b1!4m5!3m4!1s0x9c59c7ebcc28cf:0x295a1506f2293e63!8m2!3d-14.235004!4d-51.92528


Solution

  • I think I got why I'm getting inaccurate distance/results, Although it is not a solution to my problem, however now I know about the reason If someone knows best reason or solution then I'm in wait, Thank you

    MongoDB assumes earth is perfect sphere and uses average radius of earth to calculate distance between two points. But as you know earth is not sphere but more sort of Ellipsoid so distance calculation will not be perfect but approximate in MongoDB. However, Google uses a very complex formula to get better results. They do have huge database of radius of the earth at different locations on earth.