开发者

MongoDB 1.6.5: how to rename field in collection

$rename function is available only in de开发者_Python百科velopment version 1.7.2. How to rename field in 1.6.5?


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)


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜