Domanda

Hi this is a newbie question to mongodb Geospatial near query - there are unknown points exist in the distance from current user point, I need to find the furthest point (given a distance range) from current point.

But seems near only sorts it by the order of the distance Ascending (or nearest), so the question is how can I get the Geo results sorted by distance descending ( furthest )?

Thanks!!

È stato utile?

Soluzione

No code in your question so I guess I'll just steal from the documentation then.

The catch is actually having a "distance" field to sort on, and the $near operator caters for the general case that people "expect" things to be in the "nearest" order.

But you can do this with the aggregation framework and the $geoNear operator there:

db.places.aggregate([
    // Must be the the "first" pipeline stage
    { "$geoNear": {
        "near": [40.724, -73.997],
        "distanceField": "dist.calculated",
        "maxDistance": 0.008,
        "query": { "type": "public" },
        "includeLocs": "dist.location",
        "num": 5
    }},

    // Now you have something to sort on, so furthest comes first
    { "$sort": { "dist.calculated": -1 } },

    // And return only 1
    { "$limit": 1 }
])

But please note that what this does is to find the "furthest" possible location from the point you were querying "near" and only "within" the constraints you bound to the query and up to a possible 100 results.

The full options spec is on the manual page.

To actually find the "furthest" point from a full data-set is a kind of counter intuitive usage of near as in the purpose it is designed for.

As a note to that last point, there is no "furthest" operator as such and mostly because it seems to lack a lot of practical usages.

But hopefully you actually meant what was described and that does have a practical use for you, and that I hope that is what your question actually did ask for.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top