Mongo中$ $和$ centerSphere之间的区别?

时间:2018-01-30 13:49:26

标签: mongodb geospatial geo

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

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

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

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

1 个答案:

答案 0 :(得分:2)

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

关于$geoWithin,它不接受以英里为单位的距离,而是以坐标系统使用的单位测量的圆的半径,所以纬度和经度均为documentation。这导致了一个非常大的边界框,其中包括Albuquerque

bounding box

您可以使用$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
      ]
   }
}