Last active
April 8, 2022 19:41
-
-
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.
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
/* | |
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