Search code examples
mongodbindexingunique-constraintsparse-matrix

Change a unique index to a sparse unique index in mongo db?


If I have a collection that has a unique index on a field like this:

collection.User.ensureIndex({username:1}, {unique: true})

How can I change it so that the index is unique and sparse? Running the following doesn't seem to update the index:

collection.User.ensureIndex({username:1}, {unique: true, sparse:true})


Solution

  • ensureIndex creates an index on the specified field if the index does not already exist. If you want to change an index, you have to drop the index first and then call ensureIndex again with your new options.

    collection.User.dropIndex("username_1");
    collection.User.ensureIndex({username:1}, {unique: true, sparse:true})
    

    Taken from the mongodb documentation:

    To add or change index options you must drop the index using the dropIndex() method and issue another ensureIndex() operation with the new options.