Navigation
This version of the documentation is archived and no longer supported.

Modify an Index

To modify an existing index, you need to drop and recreate the index.

1

Create a unique index.

Use the ensureIndex() method create a unique index.

db.orders.ensureIndex(
   { "cust_id" : 1, "ord_date" : -1, "items" : 1 },
   { unique: true }
)

The method returns a document with the status of the results. The method only creates an index if the index does not already exist. See Create an Index and Index Creation Tutorials for more information on creating indexes.

2

Attempt to modify the index.

To modify an existing index, you cannot just re-issue the ensureIndex() method with the updated specification of the index.

For example, the following operation attempts to remove the unique constraint from the previously created index by using the ensureIndex() method.

db.orders.ensureIndex(
   { "cust_id" : 1, "ord_date" : -1, "items" : 1 }
)

The status document returned by the operation shows an error.

3

Drop the index.

To modify the index, you must drop the index first.

db.orders.dropIndex(
   { "cust_id" : 1, "ord_date" : -1, "items" : 1 }
)

The method returns a document with the status of the operation. Upon successful operation, the ok field in the returned document should specify a 1. See Remove Indexes for more information about dropping indexes.

4

Recreate the index without the unique constraint.

Recreate the index without the unique constraint.

db.orders.ensureIndex(
   { "cust_id" : 1, "ord_date" : -1, "items" : 1 }
)

The method returns a document with the status of the results. Upon successful operation, the returned document should show the numIndexesAfter to be greater than numIndexesBefore by one.