通过shell脚本查询mongodb中的地理空间数据看起来很直接,但是,我正试图在morphia(playmorphia)中复制一些代码。
获取特定半径范围内的所有积分,文档说:
> center = [50, 50]
> radius = 10
> db.places.find({"loc" : {"$within" : {"$center" : [center, radius]}}})
这是我在Peak模型中的代码:
Double[] loc = new Double(2);
// it's set to my [Longitude, Latitude]
List<Peak> peaks = play.modules.morphia.Model.ds().find(Peak.class).field("loc").near(loc[0], loc[1], 10/111.12).limit(50).asList();
它有效,但是我使用ds()。find()做错了吗?有没有更优雅的方式来使用模型,例如Peak.find ..?谢谢!
答案 0 :(得分:0)
您需要在地理字段上放置索引。
我项目的示例代码:
@Indexed(IndexDirection.GEO2D)
public Double[] geo = new Double[2];
List<User> pharmacist = MorphiaQuery.ds()
.createQuery(User.class)
.filter("isPharmacist",true)
.field("geo")
.within(nelat, nelng, swlat, swlng)
.field("geo")
.near(u.geo[0], u.geo[1])
.limit(limit)
.asList();
查看手册: http://code.google.com/p/morphia/wiki/Query#Geo-spatial
答案 1 :(得分:0)
** @索引(IndexDirection.GEO2D) public Double [] geo = new Double [2];
public static string getResult`enter code here`() {
DB datastore = ConnectionFactory.getInstance().getDatabaseMongo();
double[] near = { 20.593684, 78.96288 };
BasicDBObject basicDBObject = new BasicDBObject();
basicDBObject.put("type", "Point");
basicDBObject.put("coordinates", near);
BasicDBObject geoNearParams = new BasicDBObject();
geoNearParams.append("geoNear", <collection name>);
geoNearParams.append("near", basicDBObject);
geoNearParams.append("spherical", true);
geoNearParams.append("maxDistance", 100);
geoNearParams.append("limit", 10);
CommandResult commandResult = datastore.command(geoNearParams);
commandResult.getErrorMessage();
Object data = commandResult.get("results");
System.out.println(data.toString());
}**