Search code examples
javamongodbfilterdocumentfilter

MongoDB query in nested key value and compare inside value list


My database looks like

{
  "_id" : ObjectId("5a8351093cf24e144d8fef24"),
  "__type" : "TrafficIncident:http://schemas.microsoft.com/search/local/ws/rest/v1",
  "point" : {
    "type" : "Point",
    "coordinates" : [
        37.410883,
        -95.71027
    ]
  },
  ...
}
{
  "_id" : ObjectId("5a8351093cf24e144d8fef25"),
  "__type" : "TrafficIncident:http://schemas.microsoft.com/search/local/ws/rest/v2",
  "point" : {
    "type" : "Point",
    "coordinates" : [
        40.2346,
        -100.826167
    ]
  },
  ...
}

If I have a coordinates pair as center location, say [38, -98], and I want to retrieve all records with in coordinate range [38 +- 2, -98 +- 2], how to write java code for the Document Filter?

So far what I have done is retrieving a specific location instead of inside a range.

Document query = new Document("point.coordinates", Arrays.asList(40.2346, -100.826167));
javamongo.collection.find(query).limit(javamongo.numLimit).forEach(printBlock);

Solution

  • You'll want to use MongoDB's Geospatial Query system for this.

    I'm assuming you're using Mongo's official Java Driver. First you'll want to create a 2dsphere index on the point.coordinates field. You can do this in Java with:

    collection.createIndex(Indexes.geo2dsphere("point.coordinates"));
    

    Then you can query for all documents within your location range with:

    Point refPoint = new Point(new Position(38, -98));
    collection.find(Filters.near("point.coordinates", refPoint, 2, 2)).forEach(printBlock);
    

    MongoDB's tutorial on geospatial search with their Java driver is pretty good.