MongoDB:将一个集合中的点与另一个集合中的多边形进行匹配

MongoDB: Matching points from one collection with polygons from another

我正在尝试将一个集合中的点与存储在另一个集合中的区域进行匹配。 以下是文档示例。

积分:

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

地区:

{
  "_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" 
  } 
}

我要构建的查询是这样的:

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

我遇到一个错误:

assert: command failed: {

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

} : aggregate failed

我注意到 $geoWithin 文档的结构与我为每个区域准备的文档的结构相同。所以我尝试了这样的查询:

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

错误相同。

我查找了地理查询,但令人惊讶的是,所有发现的提及项都有静态区域文档,而不是从集合中获取的文档。所以我想知道 - 是否有可能将点映射到两个文档集合都不是静态的并且取自数据库的区域?

遗憾的是不可能

如果$geometry可以处理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"
    }
  }
])