admin管理员组

文章数量:1291113

Given the following code:

Meteor.publish('nearestVenues', function(params){
var limit = !!params ? params.limit : 50;
params ? !!params : 50;
if (!!params && !!params.coordinates){
    return Venues.find(
        { 'location.coordinates': 
            { $near :
                { $geometry :
                  { type : "Point" ,
                    coordinates : params.coordinates 
                  },
                    $maxDistance : 6000,
                    spherical: true
                } 
            }   
        }, {limit: limit, sort: 'location.coordinates': -1 });  
} else {
    return Venues.find({}, {limit: limit});
}
});

Why am I unable to properly sort the collection once it hits the client? This works up to filtering the query at sort: 'location.coordinates': -1.

Given the following code:

Meteor.publish('nearestVenues', function(params){
var limit = !!params ? params.limit : 50;
params ? !!params : 50;
if (!!params && !!params.coordinates){
    return Venues.find(
        { 'location.coordinates': 
            { $near :
                { $geometry :
                  { type : "Point" ,
                    coordinates : params.coordinates 
                  },
                    $maxDistance : 6000,
                    spherical: true
                } 
            }   
        }, {limit: limit, sort: 'location.coordinates': -1 });  
} else {
    return Venues.find({}, {limit: limit});
}
});

Why am I unable to properly sort the collection once it hits the client? This works up to filtering the query at sort: 'location.coordinates': -1.

Share Improve this question asked May 24, 2015 at 15:32 j0ej0e 1,4511 gold badge15 silver badges17 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 9

The $near operator should already sort the results by distance. Just remove the sort option and it should give you the desired results.

From the mongodb documentation:

Sort Operation

$near sorts documents by distance. If you also include a sort() for the query, sort() re-orders the matching documents, effectively overriding the sort operation already performed by $near. When using sort() with geospatial queries, consider using $geoWithin operator, which does not sort documents, instead of $near.

本文标签: javascriptSorting mongo query by distanceStack Overflow