MongoServerError: 无法创建索引 'idx_email_unique':字段 'email' 上已存在一个具有不同选项的唯一索引
MongoServerError: Cannot create index 'idx_email_unique': a unique index on field 'email' already exists with different options
ID: database/mongodb-cannot-create-index-duplicate-key
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| MongoDB 5.0 | active | — | — | — |
| MongoDB 6.0 | active | — | — | — |
| MongoDB 7.0 | active | — | — | — |
| MongoDB 8.0 | active | — | — | — |
根因分析
同一字段上已存在的唯一索引与新创建的索引具有不同的选项(例如,排序规则、稀疏、部分过滤器表达式),导致冲突。
English
An existing unique index on the same field has different options (e.g., collation, sparse, partial filter expression) than the new index being created, causing a conflict.
官方文档
https://www.mongodb.com/docs/manual/reference/method/db.collection.createIndex/解决方案
-
列出集合上的现有索引:`db.collection.getIndexes()`。识别冲突索引并删除它:`db.collection.dropIndex('idx_email_unique')`。然后使用所需选项创建新索引:`db.collection.createIndex({email: 1}, {unique: true, name: 'idx_email_unique', collation: {locale: 'en', strength: 2}})` -
如果现有索引具有不同选项但您想保留它,将新索引重命名为不同名称:`db.collection.createIndex({email: 1}, {unique: true, name: 'idx_email_unique_v2'})`
无效尝试
常见但无效的做法:
-
Drop the existing index with db.collection.dropIndex() and recreate it with the same name but different options
50% 失败
If the existing index is being used by an application, dropping it may cause query performance degradation or application errors until the new index is created
-
Create the index with the force: true option
100% 失败
MongoDB does not support a 'force' option for index creation; this will result in a syntax error
-
Ignore the error and assume the index already exists
60% 失败
The existing index may have different collation or options, leading to unexpected behavior in queries or uniqueness enforcement