之前我写过一篇文章:MongoDB LBS经纬度查询操作,我再后续的实战中发现了一些坑,再次帮大家填一下!
Geo字段顺序问题

注意一下location
中lng
(经度),lat
(纬度),按照这个顺序查询时没问题的,但是如果库中有的是lat
纬度在前,那么,就会出现两个问题
- 无法建立
2dsphere
索引。(需要数据清洗) - 建立
2d
索引后查询不出正确的数据。
对于问题二,无法查询正确的结果,在不做数据清洗的情况下,可以使用管道查询来解决,代码如下:
db.lagou_job.aggregate([
{$project:{"location.lng" : "$location.lng","location.lat" : "$location.lat" },
{$match : {"location" : { "$geoWithin" : { "$box" : [[116.308603,39.989283] ,[116.351793,39.972033]] } } }
}
])
主要是将lng
和lat
重新命名,修改顺序后,在使用geoWithin
查询。
Spring-driver-mongodb
上面sql对应的java代码如下:
Field lngField = Fields.field("location.lng", "location.lng");
Field latField = Fields.field("location.lat", "location.lat");
AggregationOperation project = new ProjectionOperation(Fields.from(lngField, latField));
double[] box1 = {116.308603,39.989283};
double[] box2 = {116.351793,39.972033};
// 矩形
Box shape = new Box(box1, box2);
AggregationOperation boxMatch = new MatchOperation(Criteria.where("location").within(shape));
AggregationOperation skip = new SkipOperation(0);
AggregationOperation limit = new LimitOperation(15);
Aggregation agg = newAggregation(match, project, boxMatch, skip, limit);
List<Result> resultList = mongoTemplate.aggregate(agg,
"company",
Result.class).getMappedResults();
出现问题的spring-boot版本:
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.1.RELEASE</version>
</parent>
最后执行的mongo语句为:
{ "aggregate" : "company", "pipeline" :
[ { "$project" : { "location.lng" : 1, "location.lat" : 1} }, { "$match" : { "location" : { "$geoWithin" : { "$java" : org.springframework.data.mongodb.core.query.GeoCommand@703ee59 } } } }, { "$skip" : { "$numberLong" : "0" } }, { "$limit" : { "$numberLong" : "15" } } ]
}
其实从这个输出的语句就能看到明显的错误了:
"$java" : org.springframework.data.mongodb.core.query.GeoCommand@703ee59
错误输出:
org.bson.codecs.configuration.CodecConfigurationException: Can't find a codec for class org.springframework.data.mongodb.core.query.GeoCommand.
问题解决:
这篇文章中的哥们,也碰到了同样的问题,之后像spring提出了一个bug:spring-jira-1986
很快spring也解决了这个问题:github-spring-data-mongodb-pull-564。
那么具体到我这个项目上,怎么办呢?

可以看到这个问题是spring-boot-starter-parent
在2.1.0版本中解决的,so,我们来愉(忐)快(忑)的升级spring-boot
的版本吧。