当我尝试使用带有Sort的NearQuery进行查询时,我在Spring中遇到了mongoTemplate的问题。排序不起作用:
Query query = new Query();
query.with(new Sort(Direction.DESC, "timeStamp"));
Criteria criteria = new Criteria();
criteria.and("type").is("MeasurementPoint");
query.addCriteria(criteria);
NearQuery queryN = NearQuery.near(p).maxDistance(new Distance(distance, Metrics.KILOMETERS)).num(range).query(query);
GeoResults<MeasurementPoint> geoPoints = mongoTemplate.geoNear(queryN, MeasurementPoint.class);
我不知道我做错了什么,但是geoResult会给我第一场比赛,而不是最后一场比赛(Sorted DESC)。所以,我认为Sort无法正常工作。
有什么想法吗?这是一个错误吗?
谢谢!
答案 0 :(得分:2)
不幸的是,不能对geoNear结果进行排序,因为它不会返回游标,默认排序是指向点的距离。您可以做的是在Java代码中手动对结果进行排序。请注意,下面的代码忽略距离并仅按&#34; timeStamp&#34;进行排序。
List<GeoResult<Person>> results = geoPoints.getContent();
Collections.sort(results, new Comparator<GeoResult<Person>>() {
@Override
public int compare(GeoResult<Person> o1, GeoResult<Person> o2) {
return o1.getContent().getTimeStamp() == 2.getContent().getTimeStamp() ? 0 :
(o1.getContent().getTimeStamp() > o2.getContent().getTimeStamp() ? 1 : -1) ;
}
});
另一种方法是使用$ geoWithin和$ centerSphere。由于您使用一定距离(距离变量)来限制结果,这可能会有效。
Query query = Query.query(Criteria.where("coords").withinSphere(new Circle(p, new Distance(distance, Metrics.KILOMETERS).getNormalizedValue())));
query.with(new Sort(Direction.DESC, "timeStamp"));
Criteria criteria = new Criteria();
criteria.and("type").is("MeasurementPoint");
query.addCriteria(criteria);
List<Person> geoPoints = mongoTemplate.find(query, MeasurementPoint.class);
您可以在此处找到有关$ geoWithin和$ centerSphere的更多信息:
http://docs.mongodb.org/manual/reference/operator/geoWithin/
http://docs.mongodb.org/manual/reference/operator/centerSphere/