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

标签 java mongodb

我的 MongoDB 数据库中有一些商店的产品遵循此数据模型: 店铺 { idShop, 名称, 位置 {lat, lon}, products [] of 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);

没有任何运气。

谁能帮我解决这个问题?

提前致谢。

最佳答案

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

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

根据mongodb文档,

The code assumes that you are using decimal degrees in (longitude, latitude) order. This is the same order used for the GeoJSON spec. Using (latitude, longitude) will result in very incorrect results, but is often the ordering used elsewhere, so it is good to double-check

同样来自 java mongodb-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));

让它发挥作用

关于java - 使用 Java 驱动程序的 MongoDB $near 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9352016/

相关文章:

node.js - 如何使用 mongoose 和 MongoDB 在我的网站中实现搜索引擎

java进程构建器添加环境路径不起作用

java - 从 Servlet 输出 HTML 的最佳实践是什么?

java - 从泛型 ArrayList 派生泛型类型

java - MongoDB Morphia - 独特的

javascript - 如何编写 Mongoose 查询来过滤子文档

mongodb - 在 Meteor.js 中,我如何让两个开发项目使用同一个 Mongo 实例?

java - 重复键 - 误导性异常信息?

java - Session 对象中的 ArrayList 似乎丢失了内容

node.js - 使用 node.js 将文件流式传输到 mongodb