How to calculate distance between two geolocation points?

Hi @NeNaD,

Would the distance calculated with distance = √ ((x2-x1)² + (y2-y1)²) work for you?

> db.coll.findOne()
{
  _id: ObjectId("62c43a4128c8b27fda436536"),
  location_1: { type: 'Point', coordinates: [ 10, 20 ] },
  location_2: { type: 'Point', coordinates: [ 10, 30 ] }
}

Aggregation:

[
  {
    '$addFields': {
      'distance': {
        '$sqrt': {
          '$add': [
            {
              '$pow': [
                {
                  '$subtract': [
                    {
                      '$arrayElemAt': [
                        '$location_2.coordinates', 0
                      ]
                    }, {
                      '$arrayElemAt': [
                        '$location_1.coordinates', 0
                      ]
                    }
                  ]
                }, 2
              ]
            }, {
              '$pow': [
                {
                  '$subtract': [
                    {
                      '$arrayElemAt': [
                        '$location_2.coordinates', 1
                      ]
                    }, {
                      '$arrayElemAt': [
                        '$location_1.coordinates', 1
                      ]
                    }
                  ]
                }, 2
              ]
            }
          ]
        }
      }
    }
  }
]

Result:

[
  {
    _id: ObjectId("62c43a4128c8b27fda436536"),
    location_1: { type: 'Point', coordinates: [ 10, 20 ] },
    location_2: { type: 'Point', coordinates: [ 10, 30 ] },
    distance: 10
  }
]

Cheers,
Maxime.

1 Like