【问题标题】:Difference between $center and $centerSphere in Mongo?Mongo中$center和$centerSphere的区别?
【发布时间】:2018-07-09 10:26:18
【问题描述】:

目前,我们正在使用 $centerSphere 来查找附近的城市。一个例子是,对于美国德克萨斯州的地区 Bee Cave,$centerSphere 正确地找到了半径 30 公里内唯一的城市奥斯汀(根据文档,它被转换为 弧度)。现在,对于斐济的劳托卡市(纬度:-17.6169618,长:177.4504609),它给出了错误“球面距离需要(未实现)包装”。这是问题一:这个错误是什么意思?

我们尝试使用 $center 来实现相同的功能。我知道我们需要以英里而不是弧度为单位给出距离。实施后,对于 Bee Cave,我得到了数千或数百英里外的美国城市。一个例子是阿尔伯克基。即使正确遵循 Mongo 文档,我也无法理解为什么这些城市会到来。

我正在使用查询(对于 Bee Cave,TX)

db.places.find{
   "geo": {
      $geoWithin: { $center: [ [ -97.9524, 30.3061 ] , 18.64 ] }
   }
}

【问题讨论】:

    标签: mongodb geospatial geo


    【解决方案1】:

    $centerSphere 无法处理很远的距离,特别是如果它必须绕到两极,请参阅此JIRA ticket

    关于$geoWithin,它不接受以英里为单位的距离,而是接受以坐标系使用的单位测量的圆的半径,因此纬度和经度按照documentation。这会产生一个非常大的边界框,其中确实包括阿尔伯克基

    您使用$near 代替它允许以米为单位指定半径。例如,如果您将其用作测试数据:

    db.places.insert( {
       name: "Bee Cave, Texas",
       location: { type: "Point", coordinates: [ -97.9524, 30.3061 ]  }
    } );
    db.places.insert( {
       name: "Austin, Texas",
       location: { type: "Point", coordinates: [ -97.654724, 30.210768 ]  }
    } );
    db.places.insert( {
       name: "Albuquerque",
       location: { type: "Point", coordinates: [ -106.621216, 35.113281 ]  }
    } );
    
    db.places.createIndex( { location: "2dsphere" } )
    

    您可以使用因子1609.344 编写以下查询以将英里转换为米

    db.places.find(
       {
         location:
           { $near:
              {
                $geometry: { type: "Point",  coordinates: [-97.9524, 30.3061 ] },
                $maxDistance: 20*1609.344 
              }
           }
       }
    )
    

    此查询返回 Bee Cave,TX 和 Austin,TX:

    {
       "_id":ObjectId("5a7190124f0cd7075d349bbc"),
       "name":"Bee Cave, Texas",
       "location":{
          "type":"Point",
          "coordinates":[
             -97.9524,
             30.3061
          ]
       }
    }{
       "_id":ObjectId("5a7190124f0cd7075d349bbd"),
       "name":"Austin, Texas",
       "location":{
          "type":"Point",
          "coordinates":[
             -97.654724,
             30.210768
          ]
       }
    }
    

    【讨论】:

    • 所以当涉及到 geoWithin 时,我必须以弧度表示距离?他们没有在 $center 的文档中指定相同的内容。至少对于 $centerSphere,他们已经明确指定我们必须使用弧度。我还是一头雾水。
    • 这是为 $center 编写的:“以下示例查询返回所有坐标存在于以 [ -74, 40.74 ] 为中心且半径为 10 的圆内的文档”。它只是说半径为 10。没有提到任何单位。
    • "圆的半径,以坐标系使用的单位测量。"
    • 这是您的情况下的纬度和经度,与您的结果相匹配(阿尔伯克基 --> 德克萨斯州蜜蜂洞)
    • 我已经更新了我的答案,以展示您如何改用$near
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-08-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-29
    相关资源
    最近更新 更多