Skip to content

Instantly share code, notes, and snippets.

@andreabalducci
Created January 18, 2013 15:42
Show Gist options
  • Select an option

  • Save andreabalducci/4565439 to your computer and use it in GitHub Desktop.

Select an option

Save andreabalducci/4565439 to your computer and use it in GitHub Desktop.
How to batch change a key on a mongodb collection
Run with
> mongo <server>/<db> mongodb_change_document_key.js
print('marking documents as "old"');
db.Commands.update({}, {
$set : { old : true}
}, false, true);
print('iterate on old documents');
var cursor = db.Commands.find({old:true}).sort({'Command.IssuedAt' : 1});
var doc = null;
do
{
var doc = cursor.hasNext() ? cursor.next() : null;
if (doc) {
var oldId = doc._id;
doc._id = ObjectId();
db.Commands.insert(doc);
db.Commands.remove({_id : oldId});
print('changed key from ' + oldId + ' to ' + doc._id);
}
}while(doc != null)
print('removing the "old" mark')
db.Commands.update({}, {
$unset : { old : 1}
}, false, true);
print('conversion done');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment