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

7
我希望您能找到附近的位置,因此插入记录如下...
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;
}

这段代码返回一个空列表。我不知道哪里出错了。求帮助!!

1
可能是如何在MongoDB中存储地理空间信息的重复问题。 - bummi
1个回答

18

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

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

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

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接