Search code examples
mongodbgeolocationgeospatial

MongoDB $geoNear operation "near" field usage


I have a collection "machine" with document


    {
        "_id" : "ac9d1db9-6a0d-47c6-97d3-a613c8dd0031",
        "pin" : {
            "machine":"test1",
            "position" : [ 
                -1.5716, 
                54.7732
            ]
        }
    }

Note: -1.5716 is lng and 54.7732 is lat

I have created a 2dsphere index on the document


    db.machine.createIndex( { 'pin.position' : "2dsphere" } )

I try with 2 different versions of query (only difference in query is the near field in geoNear pipeline stage)

Query 1:


    db.machine.aggregate(
      [
       {
           "$geoNear":{
               "near": [-0.2129092,51.5031594],
               "limit":100,
               "maxDistance":500*1000,
               "distanceField": "dist.calculated",
               "includeLocs": "dist.location",
               "distanceMultiplier":1/1000,
               "spherical": true
        }

       }
      ]
    )

Note: -0.2129092 is lng and 51.5031594 is lat

Query 2


    db.machine.aggregate(
      [
       {
           "$geoNear":{
               "near": { type: "Point", coordinates: [-0.2129092,51.5031594] },
               "limit":100,
               "maxDistance":500*1000,
               "distanceField": "dist.calculated",
               "includeLocs": "dist.location",
               "distanceMultiplier":1/1000,
               "spherical": true
        }

       }
      ]
    )

Note: -0.2129092 is lng and 51.5031594 is lat

Query 1 returns me the document and provides that this document is 5.88161133560063e-05 Kms away from the search co-ordinates

Query 2 returns me the document and provides that this document is 375.135052595944 Kms away from the search co-ordinates

I cross-verify the distance between these lng/lat on a site http://andrew.hedges.name/experiments/haversine/ and see that the distance between the document and the search co-ordinates is around 374.835 Kms

It seems Query 2 is providing the correct result but am not sure as to what is the difference between Query 1 and Query 2 and if I am using it incorrectly.

Please advise


Solution

  • Query 1 provides the distance in legacy co-ordinate pairs and Query 2 provices the distance in meters (GeoJSON) and hence both queries are using different units

    Please check the following link https://jira.mongodb.org/browse/SERVER-16652?jql=text%20~%20%22geoNear%22