首页 > 解决方案 > 查找区域内的地理点

问题描述

如何在 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

https://mongoplayground.net/p/xwRyKoEXlBI

标签: mongodbgeolocation

解决方案


  1. 首先,您需要将集合中的坐标类型从字符串更改为数字,请参阅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]
          }
        }
      ]
    }
  }]
)
  1. 创建2dsphere索引:
    • $geoWithin地理空间索引,几乎总能提高$geoIntersects查询的性能。
db.collection.createIndex({ location: "2dsphere" })
  1. 更正您的查询:
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]
          ]
        ]
      } 
    } 
  } 
})

我没有测试所有的流程,确保你应该克隆你的数据库并在测试集合中进行这种测试!


推荐阅读