MongoDB:将一个集合中的点与另一个集合中的多边形进行匹配 [英] 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.
积分:
{
"_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"
}
}
我试图构建的查询是这样的:
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"
}}
])
我收到一个错误:
断言:命令失败:{
"ok" : 0,
"errmsg" : "Polygon coordinates must be an array",
"code" : 2,
"codeName" : "BadValue"
} : 聚合失败
我注意到 $geoWithin 文档的结构与每个区域的结构相同.所以我尝试了这样的查询:
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"
}}
])
错误是一样的.
我查找了地理查询,但令人惊讶的是,所有提及的内容都有静态区域文档,而不是从集合中提取的文档.所以我想知道 - 是否有可能将两个文档集合都不是静态且取自 DB 的区域映射到点?
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?
推荐答案
很遗憾不可能
如果 $geometry
可以处理 MongoDB,您可以在下面执行查询 聚合表达式.
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"
}
}
])
这篇关于MongoDB:将一个集合中的点与另一个集合中的多边形进行匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!