Search code examples
javamongodbgeospatialmongodb-java

Create a geospatial query in java for mongodb


I do my project. It's related to MongoDB and Java. I need to get data which are in polygon from MongoDB.

However, my query always return No records found.

Here is my java code:

 string coords = "28.56402,79.93652a27.27569,26.16394a42.69404,20.02808a48.61541,51.37207a"
 String[] coors = coords.split("a")
 final LinkedList<double[]> polygon = new LinkedList<double[]>();
 for(int i= 0;i<coors.length;i++)
 {
    String[] coo = coors[i].split(",");
    System.out.println("coors" + i + " : " + coors[i]);
    polygon.addLast(new double[]{Double.parseDouble(coo[0]),Double.parseDouble(coo[1])});
 }
 BasicDBObject query = new BasicDBObject("loc", new BasicDBObject("$within", new BasicDBObject("$polygon", polygon)));
 FindIterable<Document> results = this.getMongoCollectionProcessor().queryDocument(query);
 MongoCursor<Document> resultsIterator = results.iterator();

This my output query:

{ "loc" : { "$within" : { "$polygon" : [ [ 28.56402 , 79.93652] , [ 27.27569 , 26.16394] , [ 42.69404 , 20.02808] , [ 48.61541 , 51.37207]]}}}

query count is zero.

What am I doing wrong? Can you help me? Thanks.


Solution

  • You can try the below query.

    Geopolygon takes array of arrays as coordinates. Use Filters.geoWithinPolygon helper method as within is deprecated.

     String coords = "28.56402,79.93652a27.27569,26.16394a42.69404,20.02808a48.61541,51.37207a";
     String[] coors = coords.split("a");
     final List<List<Double>> polygons = new ArrayList<>();
    
     for(int i= 0;i<coors.length;i++)
        {
           String[] coo = coors[i].split(",");
           System.out.println("coors" + i + " : " + coors[i]);
           polygons.add(Arrays.asList(Double.parseDouble(coo[0]),Double.parseDouble(coo[1])));
        }
    
     Bson query = Filters.geoWithinPolygon("loc", polygons);
     FindIterable<Document> results = this.getMongoCollectionProcessor().queryDocument(query);
     MongoCursor<Document> resultsIterator = results.iterator();
    

    Expected Query:

    {
        loc: {
            $geoWithin: {
                $geometry: {
                    type: "Polygon",
                    coordinates: [
                        [
                            [28.56402, 79.93652],
                            [27.27569, 26.16394],
                            [42.69404, 20.02808],
                            [48.61541, 51.37207]
                        ]
                    ]
                }
            }
        }
    }