//查询附近
@ResponseBody
@RequestMapping(value = "/geoNearN", method = RequestMethod.GET, produces = {"application/json;charset=UTF-8"})
public String testQueryMongoTopN() {
CarPointNearQuery personQuery = new CarPointNearQuery();
Random random = new Random();
double[] arr = MongoUtil.getRandomLocation();
//最多查100条记录
personQuery.setCount(100);
//随机1km米到10km
int distance = random.nextInt(10);
personQuery.setDistance(distance);
personQuery.setLongitude(arr[0]);
personQuery.setLatitude(arr[1]);
return JSON.toJSONString(mongoLbsService.geoNearCarPoint(personQuery));
}
public CarPointNearResult geoNearCarPoint(CarPointNearQuery carPointNearQuery) {
CarPointNearResult carPointNearResult = new CarPointNearResult();
if(carPointNearQuery != null && carPointNearQuery.getLongitude() != 0.0D && carPointNearQuery.getLatitude() != 0.0D) {
Point point = new Point(carPointNearQuery.getLongitude(), carPointNearQuery.getLatitude());
NearQuery near = NearQuery.near(point, Metrics.KILOMETERS);
Query query = new Query();
//数量
query.limit(carPointNearQuery.getCount() == 0?100:carPointNearQuery.getCount());
near.query(query);
//距离
near.maxDistance(new Distance(carPointNearQuery.getDistance() == 0.0D?1.0D:carPointNearQuery.getDistance(), Metrics.KILOMETERS));
near.spherical(true);
//调用DAO层,获取数据
GeoResults geoResults = this.carPointDao.geoNear(near, CarPoint.class, "carPoint");
carPointNearQuery.setCount(geoResults.getContent().size());
carPointNearQuery.setDistance(near.getMaxDistance().getValue());
carPointNearResult.setCarPointNearQuery(carPointNearQuery);
List geoResultsContent = geoResults.getContent();
ArrayList resultsList = new ArrayList();
Iterator i$ = geoResultsContent.iterator();
while(i$.hasNext()) {
GeoResult geoResult = (GeoResult)i$.next();
CarPointResult carPointResult = new CarPointResult();
carPointResult.setDistance(geoResult.getDistance().getValue());
carPointResult.setCarPoint((CarPoint)geoResult.getContent());
resultsList.add(carPointResult);
}
carPointNearResult.setCarPointList(resultsList);
return carPointNearResult;
} else {
logger.error("geoNear 参数异常");
carPointNearResult.setErrorCode(ErrorCode.PARAM_ERROR);
return null;
}
}
public GeoResults<T> geoNear(NearQuery near, Class<T> clazz, String collectionName) {
//直接使用mongoTemplate就可以了
GeoResults geoResults = this.mongoTemplate.geoNear(near, clazz, collectionName);
return geoResults;
}
mongodbcompass如何筛选 mongodb检索
转载文章标签 mongodbcompass如何筛选 mongodb地理检索 JAVA mongodb git 文章分类 MongoDB 数据库
-
如何在Rocky 9.4版本中安装Mongodb
如何在Rocky 9.4版本中安装和配置Mongodb
mongodb linux SQL