mongodb - 查找区域内的地理点
问题描述
如何在 mongodb 中搜索一个区域内的所有地理点。
我的收藏有
{
"_id": {
"$oid": "5fa2a64d267b8309fe781d98"
},
"location": {
"coordinates": ["115.880453987155", "-31.925513609342207"]
}
}
我现在想搜索这些数据以查看用户是否在里面
顶部:-31.97127、115.98367 底部:-32.11739、115.85955
我试过跑
[
{
'$search': {
'location': {
'$geoWithin': {
'$geometry': {
'type': 'Polygon',
'coordinates': [
[
115.8455154208042, -31.97458396927722
], [
115.8830653531429, -31.97460201459856
], [
115.8823782261087, -31.94124526669114
], [
115.8498438592383, -31.9409449398814
], [
115.8455154208042, -31.97458396927722
]
],
'crs': {
'type': 'name',
'properties': {
'name': 'urn:x-mongodb:crs:strictwinding:EPSG:4326'
}
}
}
}
}
}
}
]
但得到错误Remote error from mongot :: caused by :: Query should contain either operator or collector
解决方案
- 首先,您需要将集合中的坐标类型从字符串更改为数字,请参阅GeoJSON 对象示例,
{
"_id": {
"$oid": "5fa2a64d267b8309fe781d98"
},
"location": {
"coordinates": [115.880453987155, -31.925513609342207]
}
}
- 您可以尝试更新查询:
$arrayElemAt
从数组中获取特定元素$toDouble
将值转换为双倍
db.collection.updateMany(
{ "location.coordinates": { $exists: true } },
[{
$set: {
"location.coordinates": [
{
$toDouble: {
$arrayElemAt: ["$location.coordinates", 0]
}
},
{
$toDouble: {
$arrayElemAt: ["$location.coordinates", 1]
}
}
]
}
}]
)
- 创建
2dsphere
索引:$geoWithin
地理空间索引,几乎总能提高$geoIntersects
查询的性能。
db.collection.createIndex({ location: "2dsphere" })
- 更正您的查询:
- 例如,访问geospatial-tutorial
db.collection.find({
location: {
$geoWithin: {
$geometry: {
"type" : "Polygon",
"coordinates" : [
[
[115.8455154208042, -31.97458396927722],
[115.8830653531429, -31.97460201459856],
[115.8823782261087, -31.94124526669114],
[115.8498438592383, -31.9409449398814],
[115.8455154208042, -31.97458396927722]
]
]
}
}
}
})
我没有测试所有的流程,确保你应该克隆你的数据库并在测试集合中进行这种测试!
推荐阅读
- server - 服务器可以使用代理来隐藏他们的IP吗?
- c# - 无法在 C# 中计算长数据类型
- r - 如何将数据框列作为参数传递给用户定义的函数?
- java - 使用 GraphQL 的 Spring Boot OAuth2
- c - 使用 OpenMP 并行化具有未知增量条件的 for 循环
- c# - xamarin 表单 - 与选择器的两种方式绑定 - 为什么我不能从后面的代码更新选择器?
- excel - 截断到第一行的前 n 个单元格的最大值
- python - 使用 numpy 计算 2d 点变换但叉积无法计算,为什么?如何?
- ios - Swift:在 iOS 上使用 Google Places 并获得 -180 作为纬度
- git - 查看具有特定文件扩展名的文件已更改 (Git)