使用Java驱动程序进行MongoDB $near查询

3
我有一些店铺和它们在MongoDB数据库中的产品,遵循以下数据模型: 店铺 { idShop,名称,位置{纬度,经度},产品[] int } 如果我在mongoDB默认控制台中运行以下命令:
db.shops.find({products:1, location:{$near:[41.391204,2.145381]}}).limit(300)
查找按距离排序的具有产品编号1的商店,我会得到以下结果:
{ "_id" : ObjectId("4f410cefe4b03a0e3cff6f5a"), "name" : "Shop1", "location" : { "lat" : 41.389915, "lon" : 2.135628 }, "products" : [ 1, 5, 4 ] } { "_id" : ObjectId("4f410cefe4b03a0e3cff6f59"), "name" : "Shop2 Center", "location" : { "lat" : 41.388191, "lon" : 2.128816 }, "products" : [ 1, 2, 3 ] } { "_id" : ObjectId("4f410cefe4b03a0e3cff6f5c"), "name" : "Shop3", "location" : { "lat" : 41.384712, "lon" : 2.172031 }, "products" : [ 6, 1 ] } { "_id" : ObjectId("4f410cefe4b03a0e3cff6f5d"), "name" : "Shop4", "location" : { "lat" : 41.384029, "lon" : 2.173936 }, "products" : [ 6, 1, 2, 3, 4, 5 ] }
现在,我想使用我的Java Servlet获得相同的结果。如果我只按产品编号搜索,结果是正确的,但未排序。然后,如果我尝试通过添加新的键/值条件对它们进行排序,它就不返回任何东西。我正在使用以下代码:
BasicDBObject query = new BasicDBObject(); query.put("products", Integer.parseInt(idProduct)); QueryBuilder query2 = new QueryBuilder(); query2.near(Double.parseDouble(lat), Double.parseDouble(lon)); query.putAll(query2.get()); curShops = collShops.find(query);
这将返回一个空JSON。我还尝试了其他方法:

BasicDBObject query = new BasicDBObject();

query.put("products", Integer.parseInt(idProduct));

ArrayList ar = new ArrayList(2);

ar.add(Double.parseDouble(lat));

ar.add(Double.parseDouble(lon));

query.put("location", new BasicDBObject("$near", ar));

curShops = collShops.find(query);

我没有任何运气。

有人能帮我解决这个问题吗?

提前感谢。

2个回答

1

我没有使用Java驱动程序的经验,但我认为问题在这一行

 query2.near(Double.parseDouble(lat), Double.parseDouble(lon));

根据mongodb文档,

该代码假定您使用经度和纬度的十进制度数,顺序为(经度,纬度)。这是GeoJSON规范使用的相同顺序。使用(纬度,经度)将导致非常不正确的结果,但通常在其他地方使用此顺序,因此最好进行双重检查。

此外,从java mongodb-api-doc中可以看到

near

public QueryBuilder near(double x,
                         double y)

$near操作数的等效项

参数:

x - x坐标

y - y坐标

x坐标表示经度。因此,位置坐标必须传递为[lon,lat]而不是[lat,lon]

将您的查询更改为

 query2.near(Double.parseDouble(lon), Double.parseDouble(lat));

让它工作起来


0

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