To convert a non-unique index to a unique index, use the collMod command. The collMod command provides options to verify that your indexed field contains unique values before you complete the conversion.
About this Task
The collMod command converts the existing index. MongoDB scans the index for duplicate keys and then marks the index as unique.
Keep the following behavior in mind when you convert an index:
Set
prepareUniquetotruebefore you convert the index. IfprepareUniqueisfalse,collModwithunique: truereturns an error.Run the
prepareUniquemodification in a separatecollModcommand. You cannot combineprepareUniquewith other index modifications.You cannot set
prepareUniqueon an index in a time series collection. MongoDB returns an error.If another operation modifies or drops the index while
collModconverts it, the command fails. Rerun the command after the other operation completes.
For sharded collections, the following behavior also applies:
If any shard contains duplicate keys,
collModreturnsCannotConvertIndexToUnique. MongoDB does not convert the index on any shard.If the index key conflicts with the shard key, setting
prepareUniquefails. To learn which indexes can be unique on a sharded collection, see Sharded Clusters and Unique Indexes.
Before you Begin
Steps
Prepare the index to be converted to a unique index
Run collMod on the type field index and set prepareUnique to true:
db.runCommand( { collMod: "apples", index: { keyPattern: { type: 1 }, prepareUnique: true } } )
After prepareUnique is set, you cannot insert new documents that duplicate an index key entry. For example, the following insert operation results in an error:
db.apples.insertOne( { type: "Delicious", quantity: 20 } )
MongoServerError: E11000 duplicate key error collection: test.apples index: type_1 dup key: { type: "Delicious" }
Check for unique key violations
To see if there are any documents that violate the unique constraint on the type field, run collMod with unique: true and dryRun: true:
db.runCommand( { collMod: "apples", index: { keyPattern: { type: 1 }, unique: true }, dryRun: true } )
MongoServerError: Cannot convert the index to unique. Please resolve conflicting documents before running collMod again. Violations: [ { ids: [ ObjectId("660489d24cabd75abebadbd0"), ObjectId("660489d24cabd75abebadbd2") ] } ]
Note
If the response containing all conflicting document _id values exceeds 8MB, MongoDB returns the following error message instead of listing the specific violations:
Cannot convert the index to unique. Too many conflicting documents were detected. Please resolve them and rerun collMod.
In this case, resolve duplicate entries until the response is under 8MB, then run collMod again to see the remaining violations.