MongoDB - 2dsphere查询返回零结果

3

我希望通过地理空间索引从MongoDB集合中获取文档列表。我已将该集合建立2dsphere索引。

db.getCollection("Info").ensureIndex(new BasicDBObject("location", "2dsphere"), "geospatial");

一个Info文档看起来像这样。
{ "_id" : ObjectId("52631572fe38203a7388ebb5"), "location" : { "type" : "Point", "coordinates" : [  144.6682361,  -37.8978304 ] }

当我使用坐标[144.6682361,-37.8978304]查询信息集合时,返回的集合数量为零。

我正在使用JAVA API执行此操作。我的JAVA代码如下:

DBCollection coll1=db.getCollection("Info");
BasicDBObject locQuery = new BasicDBObject();
locQuery.put("near", loc);
locQuery.append("maxDistance", 3000);           
locCursor =coll1.find(locQuery);
System.out.println("LOCCURSOR"+locCursor.size());

locCursor.size()总是返回0。不确定我错在哪里。同时,我没有收到任何错误提示。只是给我返回了0个文档。有Mongo用户有什么想法吗?感谢您的时间和帮助。

1个回答

3
您可以直接将您的坐标值传递到您的查询中:
   double lat_lng_values[] = {144.6682361, -37.8978304};
    BasicDBObject geo = new BasicDBObject("$geometry", new BasicDBObject("type","Point").append("coordinates",lat_lng_values));
    BasicDBObject filter = new BasicDBObject("$near", geo);
    filter.put("$maxDistance", 3000);
    BasicDBObject locQuery = new BasicDBObject("location", filter);
    System.out.println(locQuery);

谢谢更新。我收到了消息 "errmsg" : "exception: can't find any special indices: 2d (needs index), 2dsphere (needs index), for: { loc: { $near: [ 144.6682361, -37.8978304 ], $maxDistance: 3000 } }"。我认为这是由于集合中的索引问题。但是我已经对集合进行了索引。索引语句是否有误? - Timothy Rajan
db.getCollection("Info").ensureIndex(new BasicDBObject("location.coordinates", "2dsphere"), "geospatial"); -- 这是正确的索引语句吗?还是应该使用 db.getCollection("Messages").ensureIndex(new BasicDBObject("location", "2dsphere"), "geospatial");?我不确定是应该使用 location 还是 location.coordinates? - Timothy Rajan
实现了上述代码。但是又遇到了同样的问题。甚至在cmd提示符中运行了统计信息。它说集合已经被索引。"count": 5, "size": 7984, "avgObjSize": 1596.8, "storageSize": 516096, "numExtents": 3, "nindexes": 3, "lastExtentSize": 393216, "paddingFactor": 1, "systemFlags": 1, "userFlags": 0, "totalIndexSize": 24528, "indexSizes": { "id": 8176, "geospatial": 8176 }, "ok": 1 - Timothy Rajan
不需要,可以参考文档:http://docs.mongodb.org/manual/tutorial/query-a-2dsphere-index/ - Jhanvi
无法找到如何将$geometry添加到DBObject中。 你能帮我吗? - Timothy Rajan
显示剩余11条评论

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