OPTIONS

Modify an Index

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

1

Create a unique index.

Use the createIndex() method create a unique index.

db.orders.createIndex(
   { "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 createIndex() 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 createIndex() method.

db.orders.createIndex(
   { "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.createIndex(
   { "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.

Was this page helpful?

Yes No

Thank you for your feedback!

We're sorry! You can Report a Problem to help us improve this page.