Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB 1.6.5: how to rename field in collection

Tags:

mongodb

$rename function is available only in development version 1.7.2. How to rename field in 1.6.5?

like image 833
Arty Avatar asked Jan 27 '11 05:01

Arty


People also ask

How do I rename a field in MongoDB compass?

In MongoDB, you can rename a field when updating documents in a collection. To rename a field, call the $rename operator with the current name of the field and the new name. This renames the field in all matching documents that have a field with that name.

How do I change the key name in MongoDB?

MongoDB provides different types of field update operators to update the values of the fields of the documents and $rename operator is one of them. This operator is used to update the names of the fields with new names. The new name of the field should be different from the existing name of the field.


2 Answers

The simplest way to perform such an operation is to loop through the data set re-mapping the name of the field. The easiest way to do this is to write a function that performs the re-write and then use the .find().forEach() syntax in the shell.

Here's a sample from the shell:

db.foo.save({ a : 1, b : 2, c : 3});
db.foo.save({ a : 4, b : 5, c : 6});
db.foo.save({ a : 7, b : 8 });
db.foo.find();

remap = function (x) {
  if (x.c){
    db.foo.update({_id:x._id}, {$set:{d:x.c}, $unset:{c:1}});
  }
}

db.foo.find().forEach(remap);
db.foo.find();

In the case above I'm doing an $unset and a $set in the same action. MongoDB does not support transactions across collections, but the above is a single document. So you're guaranteed that the set and unset will be atomic (i.e. they both succeed or they both fail).

The only limitation here is that you'll need to manage outside writers to keep the data consistent. My normal preference for this is simply to turn off writes while this updates. If this option is not available, then you'll have to figure out what level of consistency you want for the data. (I can provide some ideas here, but it's really going to be specific to your data and system)

like image 176
Gates VP Avatar answered Oct 03 '22 11:10

Gates VP


db.collection_name.update({}, {$rename: {"oldname": "newname"}}, false, true);

This will rename the column for each row in the collection.

Also, I discovered that if your column (the one you're renaming) appears within the index catalog (db.collection_name.getIndexes()), then you're going to have to drop and recreate the index (using the new column name) also.

like image 34
Micheal Shallop Avatar answered Oct 03 '22 13:10

Micheal Shallop