I have a MongoDB database that has a collection called fooCollection
. This collection has documents in it containing geospatial data in the way of a bounding polygon. I am using the C# MongoDB driver in my app. I noticed that it was not finding documents with certain spatial queries although it works with most of them. I emptied the collection except for one offending document and I tried to find it by executing queries directly.
My document looks like this:
{
"_id" : UUID("12345678-62d9-4024-86dc-123456789012"),
"polygon" : {
"type" : "Polygon",
"coordinates" : [ [
[ 18.414846, -33.9699577 ],
[ 18.414846, -26.0991189 ],
[ 31.0330578, -26.0991189 ],
[ 31.0330578, -33.9699577 ],
[ 18.414846, -33.9699577 ]
] ]
},
"foo": "bar"
}
I also have this index on that collection:
[
1,
{
"polygon" : "2dsphere"
},
"polygon_2dsphere",
"data.fooCollection",
3
]
The following query correctly returns this document:
db.getCollection('fooCollection').find( {
"polygon": {
$geoIntersects: {
$geometry: {
type: "LineString",
coordinates: [[24.7698287, -28.7353533],[28.0423, -26.19793]]
}}}})
However, this query does not:
db.getCollection('fooCollection').find( {
"polygon": {
$geoIntersects: {
$geometry: {
type: "LineString",
coordinates: [[27.7706902, -26.1091189],[28.0423, -26.19793]]
}}}})
If you plot those three geometries, I can't really see why one would work but not the other.
- Both lines lie entirely within the polygon
- The working line is much longer
- The working line has a bearing of between 0° and 90°, the other between 90° and 180°.
Is anyone able to explain this behaviour?
EDIT: I have also tested the points individually instead of using the LineStrings. The only one that is a hit is [24.7698287, -28.7353533]
. I do need the LineStrings - the query should be a hit even if only the edge intersects the polygon and no points lie within
You can see the geojson here or you can plot the three geometries yourself by pasting the following line into http://geojson.io/:
{"type":"GeometryCollection","geometries":[{"type":"Polygon","coordinates":[[[18.414846,-33.9699577],[18.414846,-26.0991189],[31.0330578,-26.0991189],[31.0330578,-33.9699577],[18.414846,-33.9699577]]]},{"type":"LineString","coordinates":[[27.7706902,-26.1091189],[28.0423,-26.19793]]},{"type":"LineString","coordinates":[[24.7698287,-28.7353533],[28.0423,-26.19793]]}]}