【发布时间】:2023-03-25 02:50:01
【问题描述】:
我将一些帖子保存在这样的 MongoDB 集合中:
{
"_id": {
"$oid": "56e7152edbaacc2ab1d34f20"
},
"title": "the title",
"body": "the post",
"loc": {
"lat": 40.616856,
"lng": 22.954689
},
"timestamp": "1457984814748",
"username": "User",
"fbID": "4324"
}
我想获取特定比例的帖子,比如说 2 公里。
我正在尝试查找 $near 的工作原理,但在 mongodb java 文档中找不到有关此函数的文档。如果有人知道我该怎么做或在哪里可以找到有关它的一些文档,将不胜感激。
这是我目前正在尝试的,texts 是来自 db 的集合:
QueryBuilder query = new QueryBuilder();
query.put("loc").near(22.9545545, 40.616479, 50);
MongoCursor<Document> cursor2 = texts.find((BasicDBObject) query.get()).iterator();
try {
while (cursor2.hasNext()) {
Document doc = cursor2.next();
documents.add(doc);
}
} finally {
cursor2.close();
}
我也试过这个:
Double locationLongitude = new Double (22.9545545);
Double locationLatitude = new Double (40.616479);
BasicDBObject locQuery = new BasicDBObject ();
locQuery.put("loc", new Document("$near", new Double[]{locationLongitude, locationLatitude}));
MongoCursor<Document> cursor2 = texts.find(locQuery).iterator();
try {
while (cursor2.hasNext()) {
Document doc = cursor2.next();
documents.add(doc);
}
} finally {
cursor2.close();
}
更新
经过一番研究,我得出了这个结论:
我将我的 json 文档更改为:
{
"_id": {
"$oid": "56e9e7440296451112edd05d"
},
"title": "ρ",
"body": "ρ",
"lng": 22.954689,
"lat": 40.616856,
"loc": {
"type": "Point",
"coordinates": [
22.954689,
40.616856
]
},
"timestamp": "1458169668154",
"username": "User",
"fbID": "4324"
}
和我的java代码:
collection.createIndex(new Document("loc", "2dsphere"));
MongoCursor<Document> cursor = collection.find(near("loc", 22.9548626, 40.6159144, 100.0, 0.0)).iterator();
try {
while (cursor.hasNext()) {
Document doc = cursor.next();
documents.add(doc);
}
} finally {
cursor.close();
}
但仍然没有得到任何结果.. cursor 没有文档。 我也遇到这个错误
03-17 01:34:05.489 1786-1805/? W/System.err:com.mongodb.MongoQueryException:查询失败,错误代码 17007 和错误消息“无法执行查询:错误处理查询:ns=posts2.texts2 limit=0 skip=0 03-17 01:34:05.489 1786-1805/? W/System.err:树:GEONEAR 字段=loc maxdist=100 isNearSphere=0 03-17 01:34:05.489 1786-1805/? W/System.err:排序:{} 03-17 01:34:05.489 1786-1805/? W/System.err:项目:{} 03-17 01:34:05.489 1786-1805/? W/System.err:规划器返回错误:无法在服务器 ds011439.mlab.com:11439 上找到 $geoNear 查询的索引
【问题讨论】:
-
你的 Java 代码在哪里?
-
@Saleem 我编辑了他的问题。感谢您的回复
-
我的 json 也有变化。 “lng”和“lat”在“loc”中
-
有关
$near查询的基本信息,请参阅官方文档:docs.mongodb.org/manual/reference/operator/query/near。这不是关于 Java 驱动程序,而是关于一般的 mongo。尝试使用 mongo shell 并手动运行查询,直到您能够自己编写查询,然后切换到 Java 驱动程序。此外,您可以添加一些关于您的方法失败的原因/方式的信息。 -
错误是不言自明的。
error: unable to find index for $geoNear query' on server ds011439.mlab.com:11439。不知道有什么难的