MongoDB:将一个集合中的点与另一个集合中的多边形进行匹配
我正在尝试将一个集合中的点与另一个集合中存储的区域相匹配。 以下是文档的示例 要点:MongoDB:将一个集合中的点与另一个集合中的多边形进行匹配,mongodb,mongodb-geospatial,Mongodb,Mongodb Geospatial,我正在尝试将一个集合中的点与另一个集合中存储的区域相匹配。 以下是文档的示例 要点: { "_id" : ObjectId("5e36d904618c0ea59f1eb04f"), "gps" : { "lat" : 50.073288, "lon" : 14.43979 }, "timeAdded" : ISODate("2020-02-02T1
{
"_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"
}}
])
我得到一个错误:
断言:命令失败:{
"ok" : 0,
"errmsg" : "Polygon coordinates must be an array",
"code" : 2,
"codeName" : "BadValue"
}:聚合失败
我注意到$GEOIN文档的结构与我为每个区域设置的结构相同。所以我试着这样问:
db.points.aggregate([
{$project: {
coordinates: ["$gps.lon", "$gps.lat"]
}},
{$lookup: {
from: "regions", pipeline: [
{$match: {
coordinates: {
$geoWithin: "$geometry.coordinates"
}
}}
],
as: "district"
}}
])
错误是一样的
我查找了geoqueries,但令人惊讶的是,所有提到的都是静态区域文档,而不是从集合中获取的文档。所以我想知道,是否有可能将点映射到两个文档集合都不是静态的且取自DB的区域?不幸的是,这是不可能的
如果$geometry
可以处理MongoDB,您可以执行下面的查询
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"
}
}
])