本文介绍了如何获得距离 - MongoDB 模板 Near 功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试查找附近的地点.下面的代码工作正常.但是我无法从给定的纬度,经度获得实际的地点距离.

I'm trying to find Near by places. Below code is working fine.But i'm not able to get actual distance of place from my given lat,lng.

Criteria criteria = new Criteria("coordinates")
    .near(new Point(searchRequest.getLat(),searchRequest.getLng()));

Query query = new Query();
query.addCriteria(criteria);
query.addCriteria(criteriaName);
query.limit(5);
List<Place> ls = (List<Place>) mongoTemplate.find(query, Place.class);

推荐答案

你可以用 geoNear 聚合.在 spring-data-mongodb GeoNearOperation 代表此聚合.

You can do it with geoNear aggregation. In spring-data-mongodb GeoNearOperation is representing this aggregation.

扩展或创建继承 Place 类,其中包含您希望获得距离信息的字段(使用继承的示例):

Extend or create inherit Place class with field where you would like to have distance information (example with inheritance):

public class PlaceWithDistance extends Place {
    private double distance;

    public double getDistance() {
        return distance;
    }

    public void setDistance(final double distance) {
        this.distance = distance;
    }
}

使用聚合代替 CriteriaQuery.geoNear 的第二个参数是应该设置距离的字段名称:

Instead of Criteria with Query use aggregation. Second argument of geoNear is name of field where distance should be set:

final NearQuery nearQuery = NearQuery
    .near(new Point(searchRequest.getLat(), searchRequest.getLng()));
nearQuery.num(5);
nearQuery.spherical(true); // if using 2dsphere index, otherwise delete or set false

// "distance" argument is name of field for distance
final Aggregation a = newAggregation(geoNear(nearQuery, "distance"));

final AggregationResults<PlaceWithDistance> results = 
    mongoTemplate.aggregate(a, Place.class, PlaceWithDistance.class);

// results.forEach(System.out::println);
List<PlaceWithDistance> ls = results.getMappedResults();

只是为了更容易 - 关联导入:

Just to make it easier - associated imports:

import static org.springframework.data.mongodb.core.aggregation.Aggregation.geoNear;
import static org.springframework.data.mongodb.core.aggregation.Aggregation.newAggregation;

import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.aggregation.GeoNearOperation;
import org.springframework.data.mongodb.core.query.NearQuery;

这篇关于如何获得距离 - MongoDB 模板 Near 功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-23 17:43