修复创建2dsphere索引时MongoDB中的“经度/纬度越界”的问题
如果您在尝试在MongoDB中创建2dsphere索引时遇到“经度/纬度超出界限”错误,则可能是由于您的经度和纬度坐标顺序错误。
创建 GeoJSON 对象时,需要先列出经度,然后再列出纬度。
- 有效的经度值介于 和 之间,包括两者。
-180``180 - 有效的纬度值介于 和 之间,包括两者。
-90``90
因此,如果您收到“经度/纬度超出界限”错误,请检查您的文档以查看纬度和经度坐标的顺序。
错误示例
下面是一个名为 bars 的集合示例,其中包含坐标顺序错误的文档:
{ “_id” : 1, “name” : “Boardwalk Social”, “location” : { “type” : “Point”, “coordinates” : [ -16.919297718553366, 145.77675259719823 ] } } { “_id” : 2, “name” : “The Downunder Bar”, “location” : { “type” : “Point”, “coordinates” : [ -16.92107838010542, 145.77621640842125 ] } }
如果我们尝试在字段上创建 2dsphere 索引,我们将收到错误。location
例:
db.bars.createIndex(
{ location : "2dsphere" }
)
输出:
{
"ok" : 0,
"errmsg" : "Index build failed: 2bb26869-1dec-4484-b554-3ba55fc0c0de: Collection krankykranes.bars ( e1a99ee2-b77c-41a4-b833-25c4b3c599c3 ) :: caused by :: Can't extract geo keys: { _id: 1.0, name: \"Boardwalk Social\", location: { type: \"Point\", coordinates: [ -16.91929771855337, 145.7767525971982 ] } } longitude/latitude is out of bounds, lng: -16.9193 lat: 145.777",
"code" : 16755,
"codeName" : "Location16755"
}具有正确坐标顺序的示例
这里又是集合,除了坐标顺序正确:
{ “_id” : 1, “name” : “Boardwalk Social”, “location” : { “type” : “Point”, “coordinates” : [ 145.77675259719823, -16.919297718553366 ] } } { “_id” : 2, “name” : “The Downunder Bar”, “location” : { “type” : “Point”, “coordinates” : [ 145.77621640842125, -16.92107838010542 ] } }
现在,让我们在字段上创建一个 2dsphere 索引:location
db.bars.createIndex(
{ location : "2dsphere" }
)
输出:
{
"createdCollectionAutomatically" : false,
"numIndexesBefore" : 1,
"numIndexesAfter" : 2,
"ok" : 1
}这意味着它已创建。
我们可以使用以下方法进行检查:[getIndexes()](https://database.guide/get-a-list-of-indexes-in-mongodb/ "Get a List of Indexes in MongoDB")
db.bars.getIndexes()
输出:
[
{
"v" : 2,
"key" : {
"_id" : 1
},
"name" : "_id_"
},
{
"v" : 2,
"key" : {
"location" : "2dsphere"
},
"name" : "location_2dsphere",
"2dsphereIndexVersion" : 3
}
]