Created
February 21, 2025 12:49
-
-
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
This file contains 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
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