MongoDb 在并非所有文档中的字段上创建唯一索引
问题描述:
我在生产 Mongo 数据库中添加了一个新字段,需要在其上创建唯一索引.如果我尝试创建一个,它会不断抛出异常:E11000 重复键错误索引:".
I added a new field in the production Mongo Database and need to create a unique index on it. If I try to create one it keeps throwing 'exception: E11000 duplicate key error index:'.
我知道没有新字段的文档有一个 null
值,这会导致唯一性违规.我该怎么做?
I understand documents without the new field have a null
value which is causing the uniqueness violation. How should I do it?
答
您可以使用 稀疏索引,其中仅包含具有索引字段的文档的条目.示例:
You can use Sparse Index which contain only entries for documents that have the indexed field. Example:
db.collection.createIndex( { "newIndex": 1 }, { sparse: true } )