解决 MongoDB 创建 2dsphere 索引时报“经纬度越界”错误(longitude/latitude is out of bounds)
详细分析在 MongoDB 中创建 2dsphere 地理空间索引时出现“longitude/latitude is out of bounds”错误的原因及排查解决方法,重点剖析 GeoJSON 规范中[经度, 纬度]的坐标顺序要求。
在 MongoDB 中为包含地理位置信息的文档创建 2dsphere 索引时,如果遇到类似于 Can't extract geo keys ... longitude/latitude is out of bounds(经度/纬度超出界限)的错误,通常是因为文档中的经度和纬度坐标顺序颠倒,或者数值超出了合法范围。
核心原因:GeoJSON 坐标顺序规范
在日常生活与地图 API 中,人们习惯称呼“纬度, 经度”(Latitude, Longitude)。但在标准的 GeoJSON 规范以及 MongoDB 中,坐标数组的顺序必须是先经度(Longitude),后纬度(Latitude):
$$\text{coordinates: [经度 (Longitude), 纬度 (Latitude)]}$$
同时,两者的取值范围严格限制为:
- 经度(Longitude):有效取值范围为
[-180, 180]。 - 纬度(Latitude):有效取值范围为
[-90, 90]。
如果将纬度放在第一个位置(例如某个纬度是 145.77),MongoDB 在尝试将其解析为经度时,若后续的数值超出了 [-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
]
}
}
注意观察上述文档中的 coordinates 字段:
- 第一个元素是
-16.919(实际应为南半球纬度); - 第二个元素是
145.776(实际应为东经)。
当我们在 location 字段上尝试创建 2dsphere 索引时:
db.bars.createIndex(
{ location : "2dsphere" }
);
MongoDB 会立即抛出如下错误:
{
"ok" : 0,
"errmsg" : "Index build failed: 2bb26869-1dec-4484-b554-3ba55fc0c0de: Collection test.bars :: 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"
}报错信息明确指出:lat: 145.777 超过了纬度最大值 90。
解决方案:校正坐标数组顺序
要修复此问题,需要将文档中的经度与纬度调换为正确的 [经度, 纬度] 格式:
{
"_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 索引命令:
db.bars.createIndex(
{ location : "2dsphere" }
);
输出:
{
"createdCollectionAutomatically" : false,
"numIndexesBefore" : 1,
"numIndexesAfter" : 2,
"ok" : 1
}成功返回 "ok": 1,索引构建完成。
可以使用 db.collection.getIndexes() 查看已成功创建的索引:
db.bars.getIndexes();
输出:
[
{
"v" : 2,
"key" : {
"_id" : 1
},
"name" : "_id_"
},
{
"v" : 2,
"key" : {
"location" : "2dsphere"
},
"name" : "location_2dsphere",
"2dsphereIndexVersion" : 3
}
]总结与检查建议
[!TIP]
- 坐标规范:永远牢记 GeoJSON 格式是
[Longitude, Latitude]([经度, 纬度])。- 历史脏数据排查:在建索引前,可以使用聚合管道或查询查找潜在越界数据:
db.bars.find({ $or: [ { "location.coordinates.0": { $lt: -180, $gt: 180 } }, { "location.coordinates.1": { $lt: -90, $gt: 90 } } ] });