我在mongodb java驱动程序中使用地理空间查询,使用以下代码获取给定位置周围的位置:
BasicDBObject myCmd = new BasicDBObject();
myCmd.append("geoNear", collectionName);
double[] loc = {5,5};
myCmd.append("near", loc);
myCmd.append("spherical", true);
myCmd.append("distanceMultiplier", 6378000);
myCmd.append("maxDistance", 200);
BasicDBList results = (BasicDBList)myResults.get("results");
for( Iterator< Object > it = results.iterator(); it.hasNext(); )
{
BasicDBObject result = (BasicDBObject) it.next();
BasicDBObject dbo = (BasicDBObject) result.get("obj");
System.out.println(dbo.getString("name"));
}
到目前为止,此工作正常。我遇到麻烦的地方是增加额外的选择标准。即我的集合有一个名为category的字段,我想将该类别添加到查询中。例如给我属于给定类别的所有位置。
期待收到您的答案和提示!
BR 马丁
答案 0 :(得分:0)
根据geoNear docs限制地理空间查询某些其他属性,您可以将文档添加为查询参数。
BasicDBObject myCmd = new BasicDBObject();
BasicDBObject myQuery = new BasicDBObject();
myCmd.append("geoNear", collectionName);
double[] loc = {5,5};
myCmd.append("near", loc);
myCmd.append("spherical", true);
myCmd.append("distanceMultiplier", 6378000);
myCmd.append("maxDistance", 200);
//construct a query document from another BasicDBOject
myQuery.append("category":"some category");
//add this as a query document
myCmd.append("query", myQuery);
BasicDBList results = (BasicDBList)myResults.get("results");
for( Iterator< Object > it = results.iterator(); it.hasNext(); )
{
BasicDBObject result = (BasicDBObject) it.next();
BasicDBObject dbo = (BasicDBObject) result.get("obj");
System.out.println(dbo.getString("name"));
}