Skip to content

Instantly share code, notes, and snippets.

@Gyvastis
Created September 21, 2020 13:21
Show Gist options
  • Save Gyvastis/91e0087bd6094776c2d85373efe76a5b to your computer and use it in GitHub Desktop.
Save Gyvastis/91e0087bd6094776c2d85373efe76a5b to your computer and use it in GitHub Desktop.
Rename MongoDB DBRef database name in all collections.
var newDbName = 'comsave-miner';
db.getCollectionNames().forEach(function (collName) {
var collDocsUpdated = 0;
db[collName].find().forEach(function (r) {
var refUpdated = false;
Object.keys(r).forEach(function(rKey){
if(!r[rKey]) {
return;
}
var isObject = typeof r[rKey] === 'object';
if(!isObject) {
return;
}
if (r[rKey]['$db'] && r[rKey]['$db'].length > 0) {
r[rKey]['$db'] = newDbName;
refUpdated = true;
}
else if (r[rKey].length > 0 && typeof r[rKey][0] === 'object' && r[rKey][0]['$db'] && r[rKey][0]['$db'].length > 0) {
r[rKey].forEach(function (innerR, i) {
r[rKey][i]["$db"] = newDbName;
});
refUpdated = true;
}
});
if(refUpdated) {
db[collName].replaceOne({ "_id": r._id }, r)
collDocsUpdated++;
}
});
print(collName + ' updated ' + collDocsUpdated + ' docs.')
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment