Skip to content

Instantly share code, notes, and snippets.

@XWolfOverride
Created February 21, 2025 12:49
Show Gist options
  • Save XWolfOverride/7245e290d196775602926c78a2880b15 to your computer and use it in GitHub Desktop.
Save XWolfOverride/7245e290d196775602926c78a2880b15 to your computer and use it in GitHub Desktop.
MongoDB backup and restore to local fs, designed to work on mongosh or mongodb compass shell
var bk=new (function(){
//use <database> first
const fs = require("fs");
const os = require("os")
const home=`${os.homedir()}/mongo-backup`;
function backupTo(path){
if (!path)
throw new Error("use bk.backup('directory')");
if (!fs.existsSync(path))
fs.mkdirSync(path);
db.getCollectionNames().forEach(cn=>{
let col=[];
let filename=`${home}/${path}/${cn}.json`;
db[cn].find().forEach(doc=>col.push(doc));
fs.writeFileSync(filename,JSON.stringify(col)+"\n");
print(`Ok: ${filename}`);
});
}
function restoreFrom(path){
if (!path)
throw new Error("use bk.restore('directory')");
if (!fs.existsSync(path))
return;
nukeDB();
ffs.readdirSync(`${home}/${path}`).forEach(f=>{
if (f.endsWith(".json")){
var fname=f.substring(0,f.length-5);
var json=fs.readFileSync(`${home}/${path}/${f}`,"utf-8");
json=JSON.parse(json);
db[fname].insertMany(json);
}
});
}
function nukeDB(){
db.getCollectionNames().forEach(cn=>{
db[cn].drop();
});
}
this.backup=backupTo;
this.restore=restoreFrom;
this.nuke=nukeDB;
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment