Calculate distance using geoNear with lookup

Viewed 41

I am trying to calculate distance using geoNear based on value from lookup pipeline.

For this I tried as:

db.bookDetail.aggregate([
    {
        $geoNear:{
            near: {
                type:'Point',
                coordinates[70.12,20.12]
            },
            distanceField: 'distance',
            key: 'bookcenter.address',
            spherical: true
         }
    },
    {
        $lookup:{
            from: 'books',
            localField:'book.id',
            foreignField: '_id',
            as: 'bookcenter'
        }
    }
])

It gives the bad Value error: MongoError: error processing query

And geoNear cannot be used after lookup , as I need value from lookup to pass to the key of geoNear.

Please let me know how can I calculate the distance.

If anyone needs any further information please let me know.

Note: I have latitude and longitude and want to calculate the distance from address present in books collection which is fetched using lookup

1 Answers

The $geoNear field was designed to efficiently locate point using a geospatial index. Using it to just calculate distance is a lot of unnecessary overhead.

If you aren't filtering by distance, it will be more efficient to calculate the distance on the client size with a library such as https://www.npmjs.com/package/geographiclib

Related