Calculate distance in Java Using MongoDB

本秂侑毒 提交于 2019-12-06 04:44:22

You can perform the command with the "command" method of the DB object in the Java Driver. The API documentation may be found here: http://api.mongodb.org/java/current/com/mongodb/DB.html#command%28com.mongodb.DBObject%29

Here is how the command may be performed using the Java driver:

BasicDBObject myCmd = new BasicDBObject();
myCmd.append("geoNear", "data");
double[] loc = {-73.9000, 40.7000};
myCmd.append("near", loc);
myCmd.append("spherical", true);
myCmd.append("maxDistance", (double)2500/6378137);
myCmd.append("distanceMultiplier", 6378137);
System.out.println(myCmd);
CommandResult myResult = db.command(myCmd);
System.out.println(myResult.toString());

I added some System.out.println statements, so you can see what the command document looks like, and a string representation of the results that are returned.
You can add num : 1 to the command document to limit the results to 1.

myCmd.append("num", 1);

This is noted in the geoNear documentation: http://www.mongodb.org/display/DOCS/Geospatial+Indexing#GeospatialIndexing-geoNearCommand

Hopefully this will get you started. Good luck!

DrColossos

There is a Java API available that let's you interact with it. The driver has a "command" method that does what you want.

Be sure to read the posted tutorial on the Java driver and how to translate shell commands into Java.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!