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



我的MongoDB数据库中有一些商店,上面有产品,遵循以下数据模型:商店{idShop,name,location{lat,lon},products[]of int}如果我在mongoDB默认控制台中运行以下命令:

db.stores.find({products:1,location:{$near:[41-391204,2.145381]}}).limit(300)

要找到按距离订购产品nº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]}

现在,我想要相同的结果,但使用我的javaservlet。如果我只按产品编号搜索,结果是可以的,但没有排序。然后,如果我尝试通过添加一个新的键/值条件对它们进行排序,它不会返回任何结果。我使用的代码如下:

BasicDBObject查询=新建BasicDBObject();

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

QueryBuilder query2=新建QueryBuilder();

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

query.putAll(query2.get());

curShops=collShops.find(查询);

这将返回一个空的JSON。我也尝试过其他方式,比如:

BasicDBObject查询=新建BasicDBObject();

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

ArrayList ar=新的ArrayList(2);

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

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

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

curShops=collShops.find(查询);

没有任何运气。

有人能帮我吗?

提前谢谢。

我对java驱动程序没有任何经验,但在我看来问题出在这一行

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

根据mongodb文档,

该代码假设您使用的是(经度,纬度)顺序。这与GeoJSON规范使用的顺序相同。使用(纬度、经度)会导致非常不正确的结果,但是通常是在其他地方使用的订单,所以最好仔细检查

同样从javamongodb-api-doc中,您可以看到

接近

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

使其工作

是的,这是非常直接的。我刚刚发布了一个示例,该示例将引导您在http://chuckjohnson.wordpress.com/-请参阅http://chuckjohnson.wordpress.com/2012/04/02/geospatial-location-based-searches-in-mongodb-part-2-simple-searching/

最新更新