我正在尝试将一个集合中的点与另一个集合中存储的区域进行匹配。 这是文档示例。
点:
{
"_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"
}:聚合失败
我注意到$ geoWithin文档的结构与每个区域的结构相同。所以我尝试了这样的查询:
db.points.aggregate([
{$project: {
coordinates: ["$gps.lon", "$gps.lat"]
}},
{$lookup: {
from: "regions", pipeline: [
{$match: {
coordinates: {
$geoWithin: "$geometry.coordinates"
}
}}
],
as: "district"
}}
])
错误是相同的。
我查找了地理位置,但令人惊讶的是,所有发现的提及都带有静态区域文档,而不是从馆藏中获取的。所以我想知道-是否有可能将点映射到两个文档集合都不是静态且取自DB的区域?
答案 0 :(得分:0)
如果$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"
}
}
])