Skip to content

Instantly share code, notes, and snippets.

@alexandrugheorghe
Created March 13, 2017 14:14
Show Gist options
  • Save alexandrugheorghe/4f2f45b329246d88e6141296d9658eb4 to your computer and use it in GitHub Desktop.
Save alexandrugheorghe/4f2f45b329246d88e6141296d9658eb4 to your computer and use it in GitHub Desktop.
Remove MongoDB ObjectIds and DBRefs and replaces them with their string values.
var docsQueue = [];
function processRefs(document, field)
{
for(var field in document) {
if (document[field] instanceof Array) {
for(var embededDoc in document[field]){
if (document[field][embededDoc] instanceof DBRef) {
document[field][embededDoc] = document[field][embededDoc]["$id"].str;
} else if (document[field][embededDoc] instanceof DBRef) {
document[field][embededDoc] = document[field][embededDoc].str;
} else {
docsQueue.push(document[field][embededDoc], field);
}
}
} else if (document[field] instanceof DBRef ) {
document[field] = document[field]["$id"].str;
} else if (document[field] instanceof ObjectId) {
document[field] = document[field].str;
}
}
}
db.company.find({_id: {$exists: true}}).limit(1).forEach(function(document){
docsQueue.push(document);
while(docsQueue.length > 0)
{
processRefs(docsQueue.pop());
}
printjson(document);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment