Sorting MongoDB GeoNear results by something other than distance?

試著忘記壹切 提交于 2019-12-19 09:02:53

问题


I'm developing a PHP application in which we need to retrieve results within a certain boundary, but ordered by the create date of the results, not the distance. I figured MongoDB's geoNear command would be great for this, since it takes care of calculating the distance for each result. However, I was wondering if there was a way to specify sorting by the create_date attribute, rather than distance. Ideally I would create a compound key index of coordinates and create date, and then quickly retrieve all results in a specific area ordered by create date.

Is this possible, or must I do my sorting post-query?


回答1:


However, I was wondering if there was a way to specify sorting by the create_date attribute, rather than distance...

If you're using the $near command then you have to first sort by distance or the concept of "near" doesn't really make any sense. On a globe everything can be "near" to a given point, it's just an issue of "how near".

You have two options here:

  1. limit the results of $near
  2. use the $within command

I think what you're looking for is the $within command

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

You can then sort these by some other key:

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

However, the within command may provide too many results, so you probably want to put some logic to limit the number of items returned by $within.

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

Truth is, if you hit a specific limit, the value of your $within command generally begins to drop. Your client code may want to check if you're hitting the max results.




回答2:


As i know for now you can't change default sorting, because it done internally in $near command.

Some notes from documentation:

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

So you should load collection ordered by distance, and than order by whatever you want on the client.

One more note: If you want sort by date within result sorted by distance you can do it as usual using sort( { date : -1 } ).



来源:https://stackoverflow.com/questions/5503562/sorting-mongodb-geonear-results-by-something-other-than-distance

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!