# MongoServerError: 无法提取地理键：点必须是包含 'type' 和 'coordinates' 属性的数组或对象

- **ID:** `mongodb/geo-index-2dsphere-invalid-point`
- **领域:** mongodb
- **类别:** data_error
- **验证级别:** ai_generated
- **修复率:** 90%

## 根因

在具有 2dsphere 索引的集合中，文档包含格式错误的 GeoJSON 对象，缺少必需字段（type/coordinates），或坐标值无效（例如纬度超出 ±90 或经度超出 ±180）。

## 版本兼容性

| 版本 | 状态 | 引入 | 弃用 |
|------|------|------|------|
| MongoDB 5.0 | active | — | — |
| MongoDB 6.0 | active | — | — |
| MongoDB 7.0 | active | — | — |

## 解决方案

1. ```
   使用脚本查找无效文档：`db.collection.find({ "loc": { $not: { $type: "object" } } })` 或检查缺失字段：`db.collection.find({ "loc.type": { $exists: false } })`。然后更新或删除它们。
   ```
2. ```
   使用 `db.collection.aggregate([{ $addFields: { loc: { $cond: { if: { $eq: [{ $type: "$loc" }, "array"] }, then: { type: "Point", coordinates: "$loc" }, else: "$loc" } } } }, { $out: "collection" }])` 将旧式数组转换为 GeoJSON。
   ```
3. ```
   如果坐标超出范围，进行钳制：`db.collection.updateMany({}, [{ $set: { "loc.coordinates.0": { $min: [ { $max: [ "$loc.coordinates.0", -180 ] }, 180 ] } } }])`（对纬度重复）。
   ```

## 无效尝试

- **** — The invalid documents remain in the collection and will cause the same error when the index is rebuilt or when querying. (95% 失败率)
- **** — 2dsphere indexes only support GeoJSON format; legacy pairs require a 2d index, not 2dsphere. (80% 失败率)
- **** — Human error can introduce additional malformed data; a scripted approach is safer. (60% 失败率)
