Problem using $rename on indexed fields using MongoDB

1 02 2012

Today we found a problem which occurs on MongoDB when you rename an indexed field. This problem occurs on version 2.0.2. I didn’t test the problem on another version.

If you have simple documents having the following structure:

{
    PreName : “Daniel”,
    Name: “Weber”
}

You maybe want to rename all “Name” elements to “LastName”. To do this you can use the rename functionality from MongoDB
http://www.mongodb.org/display/DOCS/Updating#Updating-%24rename

The command for a rename should be something like this:

db.MyCollection.update( { } , { $rename : { "Name " : "LastName" } } )

When you look at the documents after running the rename query everything is fine, the field name is renamed correctly.

For the reason you run the rename command again, nothing happen (as expected) because a field with “Name” doesn’t exist anymore.

The problem occurs only when you have an index on the field you want to rename. Therefore we create the same simple document and insert an index on the “Name” property with the following command:

db.MyCollection.ensureIndex( { "Name" : 1 } )

Information about index creation can be found on
http://www.mongodb.org/display/DOCS/Indexes#Indexes-Basics

Now we run the same update command. When we have a look into the database the field name changed as expected. Then we run the rename command again. A strange thing happened. The renamed field is deleted and the “LastName” value is lost.

Therefore be careful with renames of indexed elements where a script runs the rename more than once.

Advertisements

Actions

Information

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s




%d bloggers like this: