mongodb
data_error
ai_generated
true
MongoServerError: 索引构建失败:集合 mydb.mycoll 在索引 'unique_idx' 上存在重复键
MongoServerError: Index build failed: collection mydb.mycoll has duplicate keys for index 'unique_idx'
ID: mongodb/index-build-failed-due-to-duplicate-keys
90%修复率
87%置信度
1证据数
2023-06-05首次发现
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| MongoDB 6.0 | active | — | — | — |
| MongoDB 7.0 | active | — | — | — |
| MongoDB 8.0 | active | — | — | — |
根因分析
尝试创建唯一索引失败,因为集合包含索引字段的重复值。
English
An attempt to create a unique index failed because the collection contains documents with duplicate values for the indexed field(s).
解决方案
-
Identify duplicate documents using aggregation: db.mycoll.aggregate([ { $group: { _id: '$field', count: { $sum: 1 } } }, { $match: { count: { $gt: 1 } } } ]). Then delete or update duplicates. -
Use db.collection.createIndex() with { unique: true, partialFilterExpression: { field: { $exists: true } } } to skip documents missing the field if duplicates are only on missing values. -
Create a non-unique index first, then manually deduplicate data and rebuild the unique index.
无效尝试
常见但无效的做法:
-
100% 失败
The same duplicates still exist in the collection.
-
90% 失败
dropDups is removed in MongoDB 4.0+; in older versions, it deletes arbitrary duplicates.
-
80% 失败
Sparse indexes still enforce uniqueness on non-null values, so duplicates remain.