Sort MongoDB GeoNear results using something other than distance?

I am developing a PHP application in which we need to get results within a certain border, but it is ordered by the date the results were created, not by distance. I figured the MongoDB geoNear team would be useful for this, as it takes care of calculating the distance for each result. However, I was wondering if there is a way to specify sorting by the create_date attribute, not by distance. Ideally, I would create a composite key coordinate index and creation date, and then quickly retrieve all the results in a specific area, sorted by creation date.

Is this possible, or should I sort after the request?

+4
source share
2 answers

However, I was interested to know if there is a way to specify sorting by the create_date attribute, and not by distance ...

If you use the $near command, then you need to sort by distance first, or the concept of "near" doesn't really make any sense. On the globe, everything can be "close" to a given point, it is simply a question of "how close".

You have two options:

  • limit results $near
  • use the $within command

I think you are looking for the $within command

 center = [50, 50] radius = 10 db.places.find({"loc" : {"$within" : {"$center" : [center, radius]}}}) 

Then you can sort them using another key:

 db.places.find(...).sort({created:1}) 

However, there may be too many results within the command, so you probably want to set some logic to limit the number of elements returned by $within .

 db.places.find(...).limit(50).sort({created:1}) 

True, if you hit a certain limit, the value of your $within command usually starts to fall. Your client code might want to check if you have achieved maximum results.

+5
source

As I know, now you cannot change the default sort, because it is done inside the $ near command.

Some notes from the documentation :

db.places.find ({loc: {$ near: [50.50]}}) The above query finds the ones closest to (50.50) and returns them sorted by distance (there is no need for additional parameter sorting). Use limit () to specify the maximum number of points to return (a default limit of 100 applies if not defined):

Thus, you must load the collection ordered by distance, as well as the order you want on the client.

One more note. If you want to sort by date within a result sorted by distance, you can do this as usual with sort( { date : -1 } ) .

+2
source

Source: https://habr.com/ru/post/1346096/


All Articles