Reverse distance order with $near operator in MongoDB -


according mongodb documentation $near operator sort distance:

$near sorts documents distance

in order words, nearest reference point in query first element returned.

is there way of reserve order? mean, return farthest element first.

there sure way return furthest elements first, , use $geonear aggregation framework. there of course "catch", since asking antithesis of kind of search function typically used for.

as initial pipeline stage, it's job return results mandatory projected "distance" field queried point. allows add $sort pipeline stage return "distance" in "descending order". being "largest" , therefore "furthest" distance point.

basically in form this, , noting "catch":

db.collection.aggregate([     { "$geonear": {         "near": {             "type": "point",             "coordinates": [longitude,latitude]         },         "spherical": true,         "distancefield": "distance",         "limit": 999999                  // <-- that's one!     }},     { "$sort": { "distance": -1 } } ]) 

so when @ see "near" option should self explanatory, , "spherical" of course dicerns between "2d" , "2dsphere" indexes. there mentioned "distancefield" required here, , path in document calculated distance written. there 1 more important option.

as noted, general intent nearest, , such queries of nature best off returning sub-set of data indeed "nearest" queried point. means "limit" on documents return. @ documentation reveal typical "default" of 100.

so since idea reverse case, should targeting number larger total documents in collection. allow whole collection examined pipeline stage, resulting in calculated distance every document. of course it's off $sort it's thing , return documents in "furthest away" order.


is optimal? of course isn't, , rightly since asked exact opposite of "near" means word. if there "built-in" $far or $geofar operator, expect different.

but that's process. , maybe if seemingly upcoming "get me far away here possible!" application makes splash in world, maybe indeed thinking along lines you.


Comments

Popular posts from this blog

gridview - Yii2 DataPorivider $totalSum for a column -

java - Suppress Jboss version details from HTTP error response -

Sass watch command compiles .scss files before full sftp upload -