17067 mongodb config_error ai_generated true

MongoServerError: 找不到索引:{ "geometry" : "2dsphere" } 在命名空间 test.places 中

MongoServerError: Can't find index: { "geometry" : "2dsphere" } for namespace test.places

ID: mongodb/geo-2dsphere-index-missing

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

版本兼容性

版本状态引入弃用备注
mongodb-3.6 active
mongodb-4.0 active
mongodb-4.2 active
mongodb-4.4 active
mongodb-5.0 active
mongodb-6.0 active
mongodb-7.0 active

根因分析

地理空间查询或操作需要在 geometry 字段上存在 2dsphere 索引,但该索引不存在或定义不正确。

English

A geospatial query or operation requires a 2dsphere index on the geometry field, but the index does not exist or is incorrectly defined.

generic

官方文档

https://www.mongodb.com/docs/manual/core/2dsphere/

解决方案

  1. Create a 2dsphere index on the geometry field: `db.places.createIndex({geometry:'2dsphere'})`. Ensure the field contains valid GeoJSON objects.
  2. If the field name is wrong, update the query to use an existing 2dsphere index. Check existing indexes with `db.places.getIndexes()` and adjust the query field accordingly.
  3. If the data is legacy coordinate pairs, convert them to GeoJSON format using an aggregation pipeline with $addFields and $project, then create the 2dsphere index. Example: `db.places.aggregate([{$addFields:{geometry:{type:'Point',coordinates:['$lon','$lat']}}},{$out:'places'}]); db.places.createIndex({geometry:'2dsphere'})`

无效尝试

常见但无效的做法:

  1. 30% 失败

    2d index only supports legacy coordinate pairs, not GeoJSON objects like 'Point' or 'Polygon'.

  2. 10% 失败

    This does not create the required index; the query still fails.

  3. 25% 失败

    The index must be on the exact field used in the query's $near or $geoWithin.