Skip to content

Instantly share code, notes, and snippets.

@m-vdb
Last active April 8, 2022 19:41
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save m-vdb/6367480 to your computer and use it in GitHub Desktop.
Save m-vdb/6367480 to your computer and use it in GitHub Desktop.
A quick example to migrate DBRef's to ObjectId's directly in MongoDB shell.
/*
A quick example to migrate DBRef's to ObjectId's directly in MongoDB shell.
Suppose we have 2 collections:
- db.authors
- db.books, with books like {title: "My book", writer: DBRef("authors", ObjectId("anyID"))}
*/
// because of https://github.com/TylerBrock/mongo-hacker/issues/15
setAutoMulti(false);
var count = 0;
var process_field = function(x, fieldName){
if(x[fieldName] && x[fieldName].$id){
x[fieldName] = x[fieldName].$id;
}
};
var process = function(collection){
return function(x){
process_field(x, 'fieldName');
// here we can process as many fields as we want
collection.save(x);
print("Record #" + ++count);
};
};
db.books.find().forEach(process(db.books));
// and this can be easily adaptable for nested fields
/*
Rollback:
*/
var count = 0;
var rollback_field = function(x, fieldName, ref){
x[fieldName] = DBRef(ref, x[fieldName]);
};
var rollback = function(collection){
return function(x){
rollback_field(x, 'fieldName', 'refName');
// here we can process as many fields as we want
collection.save(x);
print("Record #" + ++count);
};
};
db.books.find().forEach(rollback(db.books));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment