Sot*_*her 5 geolocation mongodb geojson mongodb-query
我的mongodb集合中的文档如下所示:
{
"_id" : ObjectId("5562d6831683523f449e7d85")
"geometry" : {
"type" : "Polygon",
"coordinates" :
[[
[-122.4,37.81],
[-132.9, 39.9],
[-122.28, 37.80],
[-124.18, 39.81]
]]
}}
Run Code Online (Sandbox Code Playgroud)
我有一个点(长对),我将其称为x和y。我需要查看文档的坐标是否创建了一个多边形,以便这些坐标位于该多边形内。
因此,我当然需要计算描述多边形等各边的线,然后查看该点的坐标是否在其中。但是,现在,让我们假设我们要查询的文档具有整个数组的最大和最小经度值,x并y在其中。
这是我尝试查询此内容的方法:
db.<collection-name>.find(
{'geometry.coordinates':
{$elemMatch:
{
[{$gt:-122.1}, {$lt:-122.0 }], [{$gt: 37.89 },{$lt: 37.91}]
}
}
}
)
Run Code Online (Sandbox Code Playgroud)
但是,结果是:Unexpected token [。我试图按照这里的例子。
我如何查询这样的数组,其中文档中数组的每个元素都有条件?谢谢。
您似乎想通过匹配数组元素来尝试做的实际上是“查找包含Point的多边形”,这就是为什么我更改了您的问题标题。
要做到这一点,最好使用MongoDB的geoSpatail功能,而不是尝试自己确定范围。使用有效的GeoJSON数据,使用$geoIntersects运算符进行查询非常简单。
为了演示,我将首先建立一个包含一些Polygon数据的集合:
db.areas.insert([
{
"name": "San Jose",
"geometry": {
"type": "Polygon",
"coordinates": [[
[ -122.20916748046876, 37.13404537126446 ],
[ -122.20916748046876, 37.496652341233364 ],
[ -121.65710449218749, 37.496652341233364 ],
[ -121.65710449218749, 37.13404537126446 ],
[ -122.20916748046876, 37.13404537126446 ]
]]
}
},
{
"name": "San Franciso",
"geometry": {
"type": "Polygon",
"coordinates": [[
[ -122.73651123046874, 37.58811876638322 ],
[ -122.73651123046874, 37.89219554724437 ],
[ -122.28332519531249, 37.89219554724437 ],
[ -122.28332519531249, 37.58811876638322 ],
[ -122.73651123046874, 37.58811876638322 ]
]]
}
}
])
Run Code Online (Sandbox Code Playgroud)
然后(尽管不是特别要求$geoIntersects),当使用geoSpatial数据时,最好定义一个“索引”。对于真正的GeoJSON位置有意义的是“ 2dsphere”。索引是在包含GeoJSON数据“根”的字段上创建的,在本例中称为“ geometry”:
db.areas.createIndex({ "geometry": "2dsphere" })
Run Code Online (Sandbox Code Playgroud)
然后,您需要做的就是提供一个.find()查询。我在这里使用“旧金山市”的坐标:
db.areas.find({
"geometry": {
"$geoIntersects": {
"$geometry": {
"type": "Point",
"coordinates": [
-122.45361328124999,
37.76420119453823
]
}
}
}
})
Run Code Online (Sandbox Code Playgroud)
当然哪个返回“ Polyon”,定义“ San Franciso”区域,因为该“点”位于该对象内。
{
"name": "San Franciso",
"geometry": {
"type": "Polygon",
"coordinates": [[
[ -122.73651123046874, 37.58811876638322 ],
[ -122.73651123046874, 37.89219554724437 ],
[ -122.28332519531249, 37.89219554724437 ],
[ -122.28332519531249, 37.58811876638322 ],
[ -122.73651123046874, 37.58811876638322 ]
]]
}
}
Run Code Online (Sandbox Code Playgroud)
这就是查找“点”是否位于您存储在集合中的“多边形”之内的全部内容。
另外,请查看诸如geojsonlint.com和geojson.io之类的工具(示例,而不是认可),以验证和可视化您的数据,这些数据在您的示例中并未提供格式正确的Polygon。
| 归档时间: |
|
| 查看次数: |
1200 次 |
| 最近记录: |