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

其他格式: JSON · Markdown 中文 · English
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).

generic

解决方案

  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.

无效尝试

常见但无效的做法:

  1. 100% 失败

    The same duplicates still exist in the collection.

  2. 90% 失败

    dropDups is removed in MongoDB 4.0+; in older versions, it deletes arbitrary duplicates.

  3. 80% 失败

    Sparse indexes still enforce uniqueness on non-null values, so duplicates remain.