MongoDB-Java : List of locations with their distances from a location (lat, long)

958 views
Skip to first unread message

Alpit Gupta

unread,
Mar 11, 2016, 10:21:13 PM3/11/16
to mongodb-user

I have MongoDB database with below collection structure snippet:

....

"totalpower" : 6.8197,

"loc" : { "type" : "Point", "coordinates" : [ 38.34155548081809, 71.45369293420981 ] }

.....

I need to calculate distance(kms) and power(Watts) for 10 nearest locations to a user passed latitude/longitude.

I am bit new to MongoDB, tried digging many of the blogs and official website including indices and geoNear query but many of them makes me more confused. Some are not returning any records, i would be glad if someone guide me through a simple sample example.

Although i need to implement a REST API in java but even a thoughtful MongoDB command would be of great help!

Thanks!

Wan Bachtiar

unread,
Mar 16, 2016, 5:23:42 AM3/16/16
to mongodb-user

I need to calculate distance(kms) and power(Watts) for 10 nearest locations to a user passed latitude/longitude.

Hi Alpit,

I am not quite sure what the calculation between distance and power in your example, however to find out the 10 nearest locations you could utilise $near operator. Please see $near operator example for an example on how to execute $near through mongo shell.

Also see MongoDB Geospatial Tutorial for examples and information on geospatial.

For an example on how to perform $near in Java, see below:

import com.mongodb.MongoClient;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.MongoDatabase;
import org.bson.Document;
import java.util.Arrays;

MongoClient mongoClient;

// Connect to the local database server
mongoClient = new MongoClient();
// Get handle to "dbName" database
MongoDatabase database = mongoClient.getDatabase("dbName");
// Get a handle to the "collName" collection
MongoCollection<Document> collection = database.getCollection("collName");

// Build query 
Document query = new Document("location", 
                      new Document("$near", 
                         new Document("$geometry", 
                             new Document("type", "Point")
                                 // Note that the order is "longitude, latitude"
                                 .append("coordinates", Arrays.asList( -73.9667, 40.78) )
                         )
                         // These distances are in meters.
                         .append("$minDistance", 1000)
                         .append("$maxDistance", 5000)
        )
);
// Fetch only the first 10 matching documents. 
// By default the results are sorted from nearest to farthest.
MongoCursor<Document> cursor = collection.find(query).limit(10).iterator();
try {
    // print them out
    while (cursor.hasNext()) {
        System.out.println(cursor.next().toJson());
    }
} finally {
    cursor.close();
}
// Release resources
mongoClient.close();

The snippet above is tested using MongoDB Java Driver v3.2 and MongoDB v3.2. It is also worth pointing out that there are some significant geospatial performance improvements in MongoDB 3.2.

I am bit new to MongoDB, tried digging many of the blogs and official website

I would recommend to enrol in a free online course at MongoDB University to learn more about MongoDB. A new session for M101J: MongoDB for Java Developers has just started today so you can join straight away.

Best regards,

Wan.

Ross Lawley

unread,
Mar 16, 2016, 6:06:51 AM3/16/16
to mongod...@googlegroups.com
Great answer!

Also, just to let you know as building $near queries can be verbose, there are some helpers to make it easier see: http://mongodb.github.io/mongo-java-driver/3.2/builders/filters/#geospatial

Using the helpers this is the equivalent query:

import com.mongodb.client.model.geojson.Point;
import static com.mongodb.client.model.Filters.near;

Bson query = near("location", new Point(new Position(-73.9667, 40.78)), 5000.0, 1000.0);

Ross

--
You received this message because you are subscribed to the Google Groups "mongodb-user"
group.
 
For other MongoDB technical support options, see: http://www.mongodb.org/about/support/.
---
You received this message because you are subscribed to the Google Groups "mongodb-user" group.
To unsubscribe from this group and stop receiving emails from it, send an email to mongodb-user...@googlegroups.com.
To post to this group, send email to mongod...@googlegroups.com.
Visit this group at https://groups.google.com/group/mongodb-user.
To view this discussion on the web visit https://groups.google.com/d/msgid/mongodb-user/a3987024-3d21-464d-9fa6-04d8fd62475a%40googlegroups.com.

For more options, visit https://groups.google.com/d/optout.



--


{ name     : "Ross Lawley",
  title    : "Senior Software Engineer",
  location : "London, UK",
  twitter  : ["@RossC0", "@MongoDB"],
  facebook :"MongoDB"}

Chris De Bruyne

unread,
Mar 16, 2016, 1:09:16 PM3/16/16
to mongodb-user
+1 for builders :-)
Reply all
Reply to author
Forward
0 new messages