Search code examples
mongodbpolygongeospatialgeopolygons

mongodb - $geoIntersects sorted by overlapping percentage


I have a collection with this kind of documents:

{
  _id: ObjectId,
  type: "string", // COUNTRY, STATE, CITY
  geometry: {
    type: "MultiPolygon",
    coordinates: <coordinates>
  }
}

And I want to calculate for example in which COUNTRY is every STATE. I've tried to do this:

var state = db.entity.findOne({_id:ObjectId("someStateID")});

db.entity.find({
  geometry: {
    $geoIntersects: {
      $geometry: state.geometry
    }
  },
  type:"COUNTRY"
});

And this works just fine, excepts in some cases where the line of some STATE is touching the border of a neighbour COUNTRY where I got two or more documents.

Here is an example image

Is there a way I can sort this result by overlapping percentage? Or any kind of filter to know which one is the exact parent?


Solution

  • I've found that there is no way to do this in mongo, I had to do it with code. Here is an easy way to solve this problem