Skip to content

Instantly share code, notes, and snippets.

@iamanam
Created May 30, 2022 07:57
Show Gist options
  • Save iamanam/b600a4eace5a0549292fde424200b706 to your computer and use it in GitHub Desktop.
Save iamanam/b600a4eace5a0549292fde424200b706 to your computer and use it in GitHub Desktop.
Simple scripts to backup remote mongoDB database locally

How to use this script:

  1. At first you need to install zx node module globally using npm i -g zx. You might need to use sudo to install it globally. When installed globally you can run zx command from anywhere in command line.

  2. The script should be saved using .mjs extension and should have execute permission. To give execute permission, you can run this command chmod +x filepath .

  3. Authentication should be enabled for mongoDB and the user should have permission to use mongodump command. To create permission you can run this command from mongo shell (Mongo shell can be opened by using mongo command from terminal) . Change user and pwd value appropriately.

    use admin;
    db.createUser({
      user: 'admin', 
      pwd: 'password',
      roles: [ { role: 'root', db: 'admin' } ]
    });
    
  4. Then run the script from terminal. For example, if you saved the file with the name mongo_backup.mjs then you can do ./mongo_backup.mjs.

#!/usr/bin/env zx
const MONGO_URL = null; // you can just use mongo url rather than specifying details seperately below.
const HOST = "100.71.227.53"; // host ip address
const PORT = "27017"; // port of mongo database usually 27017
const AUTH_DB_NAME = "admin"; // usually admin
const MONGO_USERNAME = "username"; // username for mongodb
const MONGO_USERPASS = "password"; // password for the user
const MONGO_OUTPUT_DIR = "/Users/somename/Documents"; // folder where the backup will be saved
const OUTPUT_FILENAME = `${new Date().getTime()}.gz`;
const DAYS_TO_KEEP_BACKUP = 30; // how manys days backup should be kept
// check if a file exists
const fileExists = async (path) =>
!!(await fs.promises.stat(path).catch((e) => false));
// create output dir
await $`mkdir -p ${MONGO_OUTPUT_DIR}`;
// This function will remove files older than
async function removeOldFiles() {
const BACKUP_FILES = await fs.readdirSync(MONGO_OUTPUT_DIR);
BACKUP_FILES.forEach(async (file) => {
let OUTPUT_FILENAME = file.replace(".gz", "");
let fileCreateTime = parseInt(OUTPUT_FILENAME);
// delete files that are older than user specified days
if (
fileCreateTime <
new Date().getTime() - 86400000 * DAYS_TO_KEEP_BACKUP
) {
let oldFile = `${MONGO_OUTPUT_DIR}/${fileCreateTime}.gz`;
console.log(chalk.red(`Found old file: ${oldFile}. Deleting ...`));
await fs.unlinkSync(oldFile);
}
});
}
/*
if auth is enabled then user need to have necessery permission to run mongodump command
To create user with necessery permssion run this command from mongo shell
use admin;
db.createUser(
{
user: 'admin',
pwd: 'password',
roles: [ { role: 'root', db: 'admin' } ]
}
);
*/
if (MONGO_URL) {
await $`mongodump --gzip --uri ${MONGO_URL} --archive=${MONGO_OUTPUT_DIR}/${OUTPUT_FILENAME}`;
} else if (HOST && PORT && AUTH_DB_NAME && MONGO_USERNAME && MONGO_USERPASS) {
await $`mongodump --host ${HOST} --port ${PORT} --authenticationDatabase ${AUTH_DB_NAME} -u ${MONGO_USERNAME} -p ${MONGO_USERPASS} --gzip --archive=${MONGO_OUTPUT_DIR}/${OUTPUT_FILENAME}`;
if (fileExists(`${MONGO_OUTPUT_DIR}/${OUTPUT_FILENAME}`)) {
console.log(chalk.green(`Backup created : ${OUTPUT_FILENAME}`));
}
}
removeOldFiles();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment