Difference between $ geoWithin and $ geoIntersects operators?

What is the difference between operators $geoWithin

and $geoIntersects

in mongoDB?

If I search for coordinates (using the default coordinate system) $geoWithin

and $geoIntersects

return the same result.

Please correct me if I am wrong.

Any simple use case to understand the difference would be appreciated.

+3


source to share


1 answer


From $ geoIntersects :

Selection of documents, geospatial data of which intersect with the specified GeoJSON object; those. when the intersection of the data and the given object is not empty. This includes cases where the data and the specified object share an edge.

From $ geoWithin :



A selection of geospatial data documents that exist entirely within a specific form.

Let's take the following example:

> db.test.drop()
> var poly1 = { "type" : "Polygon", "coordinates" : [[[0, 0], [3, 0], [0, 3], [0, 0]]] }
> var poly2 = { "type" : "Polygon", "coordinates" : [[[1, 1], [2, 1], [1, 2], [1, 1]]] }
// poly1 is a similar triangle inside poly2
> var poly3 = { "type" : "Polygon", "coordinates" : [[[1, 0], [-2, 0], [1, 3], [1, 0]]] }
// poly3 is poly1 flipped around its "vertical" edge, then bumped over one unit, so it intersects poly1 but is not contained in it
> db.test.insert({ "loc" : poly2 })
> db.test.insert({ "loc" : poly3 })
> db.test.ensureIndex({ "loc" : "2dsphere" })
> db.test.find({ "loc" : {
    "$geoIntersects" : {
        "$geometry" : poly1
    }
} })
// poly2 and poly3 returned
> db.test.find({ "loc" : {
    "$geoWithin" : {
        "$geometry" : poly1
    }
} })
// poly2 returned

      

+7


source







All Articles