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

how store latitude and longitude in mongodb collection? and How to use it with Spring?

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

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

然后在终端上执行查询。

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;
}

此代码返回空列表。我没有明白我哪里出错了。求助!!

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

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

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

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