10

I am undertaking an effort to produce drop/create scripts for our MongoDB deployment. We would like to get to a place where all MongoDB database/collections are structurally identical across our dev, test, and production environments. To this end, we have decided to name the indexes at ensureIndex time. The problem is, how do I update the name of indexes that already exist? What I know doesn't work is just re-running the ensureIndex with a "name" specified like....

// existing indexes, note its name is "groups_1"...
dmReplSet:PRIMARY> db.system.indexes.find();
{ "v" : 1, "key" : { "groups" : 1 }, "ns" : "test.config", "name" : "groups_1" }
...

// attempt to change its name by re-issue ensureIndex command...
dmReplSet:PRIMARY> db.config.ensureIndex( { "groups" : 1 }, { "name" : "config_groups_ix" } );

// Nope, name is still "groups_1"...
dmReplSet:PRIMARY> db.system.indexes.find();
{ "v" : 1, "key" : { "groups" : 1 }, "ns" : "test.config", "name" : "groups_1" }
...

How can I update the name of a mongo index that already exists? Is there any risk in doing this?

5
  • 1
    I think you'd have to drop the existing index and then re-create it with your desired name. Commented Oct 11, 2012 at 19:21
  • Thanks, but I'm hoping there is a better way. Two of my production indexes are on a collection thats pretty big; 16 million docs and growing. Commented Oct 11, 2012 at 21:24
  • 3
    Ugh. Just checked in with the 10gen guys. @JohnnyHK is correct. You can't rename and index in mongo. You can only drop and recreate it. Sigh. Commented Oct 11, 2012 at 22:10
  • I should add that Mongo 2.2 has this restriction. Who knows what the future may hold. Commented Oct 11, 2012 at 22:18
  • 2
    There is now a feature request SERVER-7337 for renaming indexes :) Commented Oct 12, 2012 at 0:33

1 Answer 1

10

Sadly, this is impossible. The official documentation suggests to drop and recreate the index.

Update: This answer is still valid for MongoDB version 6.0.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.