简体   繁体   English

按距离排序mongo查询

[英]Sorting mongo query by distance

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. 这可以在sort:'location.coordinates':-1处过滤查询。

The $near operator should already sort the results by distance. $near运算符应该已经按距离对结果进行排序。 Just remove the sort option and it should give you the desired results. 只需删除排序选项,它应该会给你想要的结果。

From the mongodb documentation: 从mongodb文档:

Sort Operation 排序操作

$near sorts documents by distance. $near距离排序文件。 If you also include a sort() for the query, sort() re-orders the matching documents, effectively overriding the sort operation already performed by $near . 如果还为查询包含sort(),则sort()会重新排序匹配的文档,从而有效地覆盖$near已执行的排序操作。 When using sort() with geospatial queries, consider using $geoWithin operator, which does not sort documents, instead of $near. 将sort()与地理空间查询一起使用时,请考虑使用$ geoWithin运算符,它不对文档进行排序,而不是$ near。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM