mongodb data_error ai_generated true

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

MongoServerError: Can't extract geo keys: Point must be an array or object with 'type' and 'coordinates' properties

ID: mongodb/geo-index-2dsphere-invalid-point

其他格式: JSON · Markdown 中文 · English
90%修复率
88%置信度
1证据数
2023-06-20首次发现

版本兼容性

版本状态引入弃用备注
MongoDB 5.0 active
MongoDB 6.0 active
MongoDB 7.0 active

根因分析

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

English

Documents in a collection with a 2dsphere index contain GeoJSON objects that are malformed, missing required fields (type/coordinates), or have invalid coordinate values (e.g., latitude outside ±90 or longitude outside ±180).

generic

官方文档

https://www.mongodb.com/docs/manual/geospatial-queries/

解决方案

  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 ] } } }])`(对纬度重复)。

无效尝试

常见但无效的做法:

  1. 95% 失败

    The invalid documents remain in the collection and will cause the same error when the index is rebuilt or when querying.

  2. 80% 失败

    2dsphere indexes only support GeoJSON format; legacy pairs require a 2d index, not 2dsphere.

  3. 60% 失败

    Human error can introduce additional malformed data; a scripted approach is safer.