I am trying to create a unique key on a collection. It fails with the error message:
> db.users.createIndex({userid:1},{unique:true})
{ "ok" : 0, "errmsg" : "E11000 duplicate key error collection: library.users index: userid_1 dup key: { : null }", "code" : 11000 }
What am I doing wrong?
When a new index is created, all existing documents must have one. If they don't, a null value is assigned.
When you create a unique index there can be only one (or none) pre-existing document without that index.
If there are multiple documents with that index missing, then index build fails. Null value cannot be assigned to more than one documents because of the unique constraint.
Solution: Remove pre-existing documents without index or assign unique values manually.
sonja, thanks!
I removed two documemnts that were already there and issued createIndex command again, it worked!
- thank you so much ı solved my problem :) 5 years ago