Reputation: 1011
Using $near with mongodb, returns results by distance. Is there a way to know the sort order (or specify it) when distances match?
For example, if I request 10 documents and they're all the same distance and then request another 10 documents and they're also the same distance with the first set, what field can I sort on to ensure the sort order is always the same?
Upvotes: 2
Views: 1622
Reputation: 11671
$near
and $geoNear
sort by distance and the order is not defined for things at the same distance from the input point. You can use an aggregation with $geoNear
to sort based on distance + another field to ensure a consistent order:
db.test.aggregate([
{ "$geoNear" : {
"near" : { "type" : "Point", "coordinates" : [-73, 40] },
"distanceField" : "dist",
"maxDistance" : 2,
"spherical" : true
} },
{ "$sort" : { "dist" : 1, "_id" : 1 } }
])
The $sort
stage will not be able to use an index, but hopefully performance won't be too bad because the results will already be sorted by dist
.
Upvotes: 4