MongoDB - Java | Use of $near

Viewed 1302

I am saving some posts in a MongoDB Collection like this:

{
    "_id": {
        "$oid": "56e7152edbaacc2ab1d34f20"
    },
    "title": "the title",
    "body": "the post",
    "loc": {
       "lat": 40.616856,
       "lng": 22.954689
    },
    "timestamp": "1457984814748",
    "username": "User",
    "fbID": "4324"
}

I want to get the posts that are around a specific ratio lets say 2km.

I am trying to find how the $near works but cannot find documentation about this function in mongodb java docs. If anybody knows how I can do this or where can I find some documentation about it would be much appreciated.

This is what i am trying so far where texts is the collection from the db:

        QueryBuilder query = new QueryBuilder();
        query.put("loc").near(22.9545545, 40.616479, 50);
        MongoCursor<Document> cursor2 = texts.find((BasicDBObject) query.get()).iterator();
        try {
            while (cursor2.hasNext()) {
                Document doc = cursor2.next();
                documents.add(doc);
            }
        } finally {
            cursor2.close();
        }

I also tried this:

Double locationLongitude = new Double (22.9545545);
                Double locationLatitude = new Double (40.616479);
                BasicDBObject  locQuery = new BasicDBObject ();
                locQuery.put("loc", new Document("$near", new Double[]{locationLongitude, locationLatitude}));
MongoCursor<Document> cursor2 = texts.find(locQuery).iterator();
            try {
                while (cursor2.hasNext()) {
                    Document doc = cursor2.next();
                    documents.add(doc);
                }
            } finally {
                cursor2.close();
            }

UPDATE

After a little research i came to this:

I changes my json documents to this:

{
    "_id": {
        "$oid": "56e9e7440296451112edd05d"
    },
    "title": "ρ",
    "body": "ρ",
    "lng": 22.954689,
    "lat": 40.616856,
    "loc": {
        "type": "Point",
        "coordinates": [
            22.954689,
            40.616856
        ]
    },
    "timestamp": "1458169668154",
    "username": "User",
    "fbID": "4324"
}

and my java code to this:

        collection.createIndex(new Document("loc", "2dsphere"));
        MongoCursor<Document> cursor = collection.find(near("loc", 22.9548626, 40.6159144, 100.0, 0.0)).iterator();

        try {
            while (cursor.hasNext()) {
                Document doc = cursor.next();
                documents.add(doc);
            }
        } finally {
            cursor.close();
        }

But still not getting any results.. cursor has no documents. I am also getting this error

03-17 01:34:05.489 1786-1805/? W/System.err: com.mongodb.MongoQueryException: Query failed with error code 17007 and error message 'Unable to execute query: error processing query: ns=posts2.texts2 limit=0 skip=0 03-17 01:34:05.489 1786-1805/? W/System.err: Tree: GEONEAR field=loc maxdist=100 isNearSphere=0 03-17 01:34:05.489 1786-1805/? W/System.err: Sort: {} 03-17 01:34:05.489 1786-1805/? W/System.err: Proj: {} 03-17 01:34:05.489 1786-1805/? W/System.err: planner returned error: unable to find index for $geoNear query' on server ds011439.mlab.com:11439

3 Answers

First Open a shell connection to your database and create the index.

db.Salons.createIndex({"loc":"2dsphere"});

When you want to index nested object:

db.Salons.createIndex({"address.loc":"2dsphere"});

This is an alternative way to query the $near

//Imports
import org.springframework.data.geo.Circle;
import org.springframework.data.geo.Distance;
import org.springframework.data.geo.Metrics;
import org.springframework.data.geo.Point;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
    ....

Find salons near a location

Point point  = new Point(longitude, latitude);
List<Salon> salonsNear = mongoTemplate.find(new Query(Criteria
                              .where("loc")
                              .near(point)
                              .maxDistance(100)), Salon.class);

Find within a radius of 2km

Double longitude = 4.368333;
Double latitude = 51.1981366;
Double distance  = 2.0;

Circle myCircle = new Circle(new Point(longitude, latitude), new Distance(distance, Metrics.KILOMETERS));
List<Salon> salonsWithinCircle = mongoTemplate.find(new Query(Criteria
                                   .where("loc")
                                   .withinSphere(myCircle)), Salon.class);

Find within a radius of 2km for nested objects

Circle myCircle = new Circle(new Point(longitude, latitude), new Distance(distance, Metrics.KILOMETERS));
List<Salon> salonsWithinCircle = mongoTemplate.find(new Query(Criteria
                                   .where("address.loc")
                                   .withinSphere(myCircle)), Salon.class);
Related