# MongoServerError: 索引构建失败：集合 mydb.mycoll 在索引 'unique_idx' 上存在重复键

- **ID:** `mongodb/index-build-failed-due-to-duplicate-keys`
- **领域:** mongodb
- **类别:** data_error
- **验证级别:** ai_generated
- **修复率:** 90%

## 根因

尝试创建唯一索引失败，因为集合包含索引字段的重复值。

## 版本兼容性

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

## 解决方案

1. ```
   Identify duplicate documents using aggregation: db.mycoll.aggregate([ { $group: { _id: '$field', count: { $sum: 1 } } }, { $match: { count: { $gt: 1 } } } ]). Then delete or update duplicates.
   ```
2. ```
   Use db.collection.createIndex() with { unique: true, partialFilterExpression: { field: { $exists: true } } } to skip documents missing the field if duplicates are only on missing values.
   ```
3. ```
   Create a non-unique index first, then manually deduplicate data and rebuild the unique index.
   ```

## 无效尝试

- **** — The same duplicates still exist in the collection. (100% 失败率)
- **** — dropDups is removed in MongoDB 4.0+; in older versions, it deletes arbitrary duplicates. (90% 失败率)
- **** — Sparse indexes still enforce uniqueness on non-null values, so duplicates remain. (80% 失败率)
