Created
January 18, 2013 15:42
-
-
Save andreabalducci/4565439 to your computer and use it in GitHub Desktop.
How to batch change a key on a mongodb collection
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Run with | |
| > mongo <server>/<db> mongodb_change_document_key.js |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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