在区域内找到 geo-points

find geo-points inside area

如何搜索 mongodb.

区域内的所有地理点

我的collection有

{
    "_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

如果您可以从地图中提取几何点以形成“多边形”,那么您可以使用 $geoWithin 搜索在其中搜索您的点: GeoWithin search

  1. 首先,您需要将集合中的坐标类型从字符串更改为数字,请参阅 GeoJSON Objects 示例,
{
    "_id": {
        "$oid": "5fa2a64d267b8309fe781d98"
    },
    "location": {
        "coordinates": [115.880453987155, -31.925513609342207]
    }
}
  • 您可以尝试更新查询:
  • $arrayElemAt 从数组中获取特定元素
  • $toDouble 将值转换为 double
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]
          ]
        ]
      } 
    } 
  } 
})

I have not tested all the flow, make sure you should clone your database and do this kind of testing in the testing collection!