如何在mongodb集合中存储纬度和经度?以及如何在Spring中使用它?

时间:2015-03-25 07:30:57

标签: mongodb spring-mvc geolocation

我想找到附近的位置,所以插入这样的记录..

db.locationcol.insert({"location":"phase 8,mohali ,punjab ,india","service":"psychologist","loc":{"lon":76.703347,"lat":30.710459}})

然后在终端上执行Query。

db.runCommand(
{
geoNear: "locationcol",
near: { type: "Point", coordinates: [ 76.720845, 30.712097 ] },
spherical: true,
query: { category: "public" }
})

但它正在回归..

{ "ok" : 0, "errmsg" : "no geo indices for geoNear" }

我也在尝试使用Spring ......

public GeoResults getnearby(double longitude,double latitude, String service) {

Point point = new Point(longitude,latitude);

Query query = new Query(Criteria.where("service").is(service));

query.fields().include("service").include("location").include("loc");

NearQuery nearQuery = NearQuery.near(point).maxDistance(new Distance(50, Metrics.KILOMETERS));
nearQuery.query(query);
nearQuery.num(20);

GeoResults<locationcol> data = operations.geoNear(nearQuery, locationcol.class,"locationcol");

return data;
}

此代码返回空列表。我没有得到我出错的地方。帮助!!

1 个答案:

答案 0 :(得分:12)

在执行地理空间查询之前,您需要创建geospatial index

db.locationcol.createIndex( { loc : "2dsphere" } )

此外,您需要将您的位置存储为有效的GeoJSON对象,以便MongoDB可以正确解析它们:

loc : { type: "Point", coordinates: [ -76.703347, 30.710459 ] },