MongoDB 查询带有切口的点

问题描述 投票:0回答:1

在我的

lootPoint
集合中,我有这样的数据:

{
    "_id" : "1856132932",
    "point" : {
        "type" : "Point",
        "coordinates" : [ 
            21.6550408, 
            50.1034841
        ]
    }
}

{
    "_id" : "2184534902",
    "point" : {
        "type" : "Point",
        "coordinates" : [ 
            21.6560194, 
            50.1037961
        ]
    }
}

我想查询一个随机点,将正方形与中间的圆形20m切口相匹配:

enter image description here

使用互联网和人工智能,我成功地组装了以下内容:

db.lootPoint.aggregate([
  {
    $match: {
      "point.coordinates": {
        $geoWithin: {
          $geometry: {
            type: "Polygon",
            coordinates: [
              [
                  [21.654939727403415,50.10333291665514],
                  [21.656736672596585,50.10333291665514],
                  [21.656736672596585,50.10453288334485],
                  [21.654939727403415,50.10453288334485],
                  [21.654939727403415,50.10333291665514]
              ]
            ]
          }
        },
        $not: {
          $geoWithin: {
            $centerSphere: [[21.6558382, 50.1039329], 20 / 3963.2]
          }
        }
      }
    }
  },
  { $sample: { size: 1 } }
])

在 Robo3T 中运行此命令时,我收到错误: can't parse field $not...

我尝试用 $and 和 $ 重写查询,但不是这样:

db.lootPoint.aggregate([
  {
    $match: {
      $and:[
        { "point.coordinates": {...} },
        { "point.coordinates": { $not:[ ... ] } },
      ]
    }
  },
  ...

但它带来了 0 个结果。

我做错了什么? 如何使这个查询有效? 还有其他方法吗?

mongodb mongodb-query geolocation
1个回答
0
投票

您使用

$and
的查询看起来是正确的。问题可能是您的米到弧度的转换可能是错误的

根据docs除以

3963.2
用于将英里转换为弧度。同样,docs 还指出,要将 km 转换为弧度,您必须除以
6378.1
。因此要将米转换为弧度必须除以
6378100

db.collection.aggregate([
  {
    $match: {
      $and: [
        {
          "point.coordinates": {
            $geoWithin: {
              $geometry: {
                type: "Polygon",
                coordinates: [[
                  [21.654939727403415, 50.10333291665514],
                  [21.656736672596585, 50.10333291665514],
                  [21.656736672596585, 50.10453288334485],
                  [21.654939727403415, 50.10453288334485],
                  [21.654939727403415, 50.10333291665514]
                ]]
              }
            }
          }
        },
        {
          "point.coordinates": {
            $not: {
              $geoWithin: {
                $centerSphere: [
                  [21.6558382, 50.1039329],
                  0.0000031357300763550272 // 0.02/6378.1 for km to radians
                ]
              }
            }
          }
        }
      ]
    }
  }
])

https://mongoplayground.net/p/Uv5JOz8vfcb

© www.soinside.com 2019 - 2024. All rights reserved.