Working with Geofence

Hello everyone,

I am working with geolocation data and I need to determine if these data are located in a geofence defined in a collection or not.

To explain, there can be two types of geofence:

  • a Polygon type geofence
  • a circular geofence with a defined radius

In order to be able to see if a point was located in a geofence I did

  • For a circular geofence, calculated the distance from the point and the center of the circle as follow
> db.datapoints.aggregate([
    { "$geoNear": {
        "near": {
            "type": "Point",
            "coordinates": [-76.79491878920412, 39.101543051442995]
        "distanceField": "distance",
        "query": { "locationType": "circle" }
    { "$redact": {
        "$cond": {
            "if": { "$gte": [ "$distance", "$radius" ] },
            "then": "$$PRUNE",
            "else": "$$KEEP"
  • For a Polygon geofence, I am currently using this query
> db.datapoints.aggregate([
     {$match : {
         "geometry": {
             $geoIntersects: {
                     "type" : "Point",
                     "coordinates" : [ 6.1460945755351775, 49.42089640678415]
     {$project : {
                  name : "$name"}

I am now thinking about combining those 2 aggregations in order to have with only one aggregation for a given point if it is located in the circular or polygon geofence or in unknown geofence if no result returned.

Do you have any idea how can I do that? Because for now I am using both queries but I am wondering if it can be done with one aggregation pipeline.

Kind regards,


I guess you can use “similar” aggregation, not exactly the same. You can use $geoWithin which might be much better aggregations than the ones you have used.

With this stage, you can define your fence either by using $center or $polygon

So you only need to have the difference on polygon and it’s parameters between the two queries. Hope this helps you.