user1218464
user1218464

Reputation: 1011

Mongodb $near secondary sort order

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

Answers (1)

wdberkeley
wdberkeley

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

Related Questions