fgalan
fgalan

Reputation: 12294

Reverse distance order with $near operator in MongoDB

According to MongoDB documentation the $near operator sort by distance:

$near sorts documents by distance

In order words, the nearest to the reference point in the query is the first element returned.

Is there any way of reserve the order? I mean, to return the farthest element first.

Upvotes: 3

Views: 1017

Answers (1)

Blakes Seven
Blakes Seven

Reputation: 50406

There sure is a way to return the furthest elements first, and that is to use $geoNear with the aggregation framework. But there is of course a "catch", since what you are asking is actually the antithesis of what this kind of search function is typically used for.

As an initial pipeline stage, it's job is to return the results with a mandatory projected "distance" field from the queried point. This then allows you to add a $sort pipeline stage that would return the "distance" in "descending order". Being then the "largest" and therefore "furthest" distance from the point.

Basically in the form like this, and noting the "catch":

db.collection.aggregate([
    { "$geoNear": {
        "near": {
            "type": "Point",
            "coordinates": [longitude,latitude]
        },
        "spherical": true,
        "distanceField": "distance",
        "limit": 999999                  // <-- That's the one!
    }},
    { "$sort": { "distance": -1 } }
])

So when you look at that you see the "near" option which should be self explanatory, and also the "spherical" which of course dicerns between "2d" and "2dsphere" indexes. There is also as mentioned the "distanceField" which is required here, and will be the path in the document where the calculated distance is written. But there is one more important option.

As noted, the general intent is nearest, and as such most queries of this nature are best off returning just a sub-set of the data that is indeed "nearest" to the queried point. That means a "limit" on the documents to return. A look at the documentation will reveal the typical "default" of 100.

So since the idea is the reverse case, then what you should be targeting is a number that is larger than the total documents in the collection. This will allow the whole collection to be examined by the pipeline stage, resulting in a calculated distance for every document. Then of course it's just off to $sort to do it's thing and return the documents in "furthest away" order.


Is this optimal? Well of course it isn't, and rightly so since you just asked for the exact opposite of what "near" means as a word. If there were a "built-in" $far or $geoFar operator, then we could expect different.

But that's the process. And maybe if your seemingly upcoming "Get me as far away from here as possible!" application really makes a splash in the world, then maybe indeed we will all be thinking along those lines with you.

Upvotes: 4

Related Questions