Search code examples
mongodbmongodb-geospatial

MongoDB: Matching points from one collection with polygons from another


I'm trying to match points in one collection with regions stored in another collection. Here are examples of documents.

Points:

{ 
  "_id" : ObjectId("5e36d904618c0ea59f1eb04f"), 
  "gps" : { "lat" : 50.073288, "lon" : 14.43979 },  
  "timeAdded" : ISODate("2020-02-02T15:13:22.096Z") 
}

Regions:

{
  "_id" : ObjectId("5e49a469afae4a11c4ff3cf7"), 
  "type" : "Feature", 
  "geometry" : { 
    "type" : "Polygon", 
    "coordinates" : [ 
      [ 
        [ -748397.88, -1049211.61 ], 
        [ -748402.77, -1049212.2 ],
        ... 
        [ -748410.41, -1049213.11 ], 
        [ -748403.05, -1049070.62 ]
      ] 
    ] 
  }, 
  "properties" : {  
    "Name" : "Region 1" 
  } 
}

And the query I'm trying to construct is something like this:

db.points.aggregate([
  {$project: {
    coordinates: ["$gps.lon", "$gps.lat"]
  }}, 
  {$lookup: {
    from: "regions", pipeline: [
      {$match: {
        coordinates: {
          $geoWithin: {
            $geometry: {
              type: "Polygon", 
              coordinates: "$geometry.coordinates"
            }
          }
        }
      }}
    ], 
    as: "district"
  }}
])

I'm getting an error:

assert: command failed: {

    "ok" : 0,
    "errmsg" : "Polygon coordinates must be an array",
    "code" : 2,
    "codeName" : "BadValue"

} : aggregate failed

I've noticed the structure of $geoWithin document is same as structure of one I have for each region. So I tried such query:

db.points.aggregate([
  {$project: {
    coordinates: ["$gps.lon", "$gps.lat"]
  }}, 
  {$lookup: {
    from: "regions", pipeline: [
      {$match: {
        coordinates: {
          $geoWithin: "$geometry.coordinates"
        }
      }}
    ], 
    as: "district"
  }}
])

The error was same.

I looked up for geoqueries but surprisingly all found mentions had static region document instead of one taken from a collection. So I'm wondering - is it ever possible to map points with regions having that both document collections aren't static and taken from DB?


Solution

  • Unfortunately not possible

    You could perform query below if $geometry could deal with MongoDB Aggregation Expressions.

    db.points.aggregate([
      {
        $lookup: {
          from: "regions",
          let: {
            coordinates: [
              "$gps.lon",
              "$gps.lat"
            ]
          },
          pipeline: [
            {
              $addFields: {
                coordinates: "$$coordinates"
              }
            },
            {
              $match: {
                coordinates: {
                  $geoWithin: {
                    $geometry: {
                      type: "Polygon",
                      coordinates: "$geometry.coordinates"
                    }
                  }
                }
              }
            }
          ],
          as: "district"
        }
      }
    ])