Lee Morgan
Lee Morgan

Reputation: 688

Determine distance from coordinates after aggregation match

I have a set of data and I am trying to get the distance between two points using $geoNear. Here is the working code that I am using:

return Site.aggregate([
    {$geoNear: {
        near: {
            type: "Point",
            coordinates: [address.location.lat, address.location.lng]
        },
        maxDistance: 20000,
        distanceField: "distance",
    }},
    {$match: {"address.zip": address.address_components.zip}},
    {$project: {
        location: 0
    }}
]);

So this works, but it seems not ideal. I want to match on the "address.zip" field first. Then just get the distance for each result of that match. The problem is that $geoNear has to be the first stage in the aggregate.

As far as I can tell, it is kind of inefficient. I think it would be better if I could do my $match first, then just get the distance for the results. I don't even want to use the maxDistance property to check, it is unneccessary.

What I want to know, is if there is a better way to do this. Or maybe a way to get the distance without using $geoNear.

Upvotes: 0

Views: 181

Answers (1)

Buzz Moschetti
Buzz Moschetti

Reputation: 7558

Let the $geoNear optimize with the query option:

return Site.aggregate([
    {$geoNear: {
        near: {
            type: "Point",
            coordinates: [address.location.lat, address.location.lng]
        },
        // no longer needed:  maxDistance: 20000,
        distanceField: "distance",
        query: {
            "address.zip": address.address_components.zip
        }
    }}
]);

Upvotes: 1

Related Questions