MongoDB backup

2 minute read

This post explores how you can backup your MongoDB database manually or automatically using Studio 3T or mongodump for instance.

Backup with Studio 3T

Install and configure Studio 3T

Go to the official website and download Studio 3T.

Extract the software with tar:

tar xvzf studio-3t-linux-x64.tar.gz

Go into the newly created directory, and execute bin/studio3T.sh. Then configure a new connection to your server. You can find more information about how to do this in this post about Robo3T.

Backup your data

On the left panel, right click on the name of your connection, and choose Export.

  1. A window opens asking you to choose the export format
  2. Choose mongodump
  3. The next step asks you to choose between folder and archive, I choose archive
  4. The final step asks you where to write the archive.

Once you have done this you will have a mongodump that you can later import in MongoDB.

Mongo console commands

List dbs

show dbs
admin  0.078GB
local  0.078GB

Select a db

use admin

List collections

show collections

List users

show users

Backup with mongodump

From the server

mongodump --db admin --out pathToDirectory

From another machine

ssh sammy.fr mongodump --db admin --out pathToDirectory
scp sammy.fr:pathToDirectory pathToBackupDirectory

This can be put in a script that will be executed by a crontab. A user with very limited rights should be created to perform this action. The user would have only write rights in a very specific folder, and only basic read and execute rights to be able to perform the backups.

The private key should not be stored on the machine performing the backup. Instead the use of a nano Yubikey, permanently inserted in the machine will prevent malicious attackers from retrieving the private key.

Automatic backup with crontab

mongo

Create an admin user if you don’t have one

use admin
db.createUser({
  user: "admin",
  pwd: "password",
  roles: [
    {role: "clusterAdmin", db: "admin"},
    {role: "readAnyDatabase", db: "admin"},
    "readWrite"
  ]},
  {w: "majority", wtimeout: 5000})

Create a user with read only rights to perform backups:

db.createUser({
    user: "backupuser",
    pwd: "password",
    roles: ["read"]
})

Create a cron job to backup the database

# Mongodb admin backup
30 23 * * * DATE=$(date +'\%Y-\%m-\%d-\%H\%M'); mongodump --db admin -u backupuser -p password --out "/home/backupuser/backup/mongodb/admin/${DATE}_backup_mongodb"

Note that you need to escape the % character inside the cron editor when formatting the date. You also need to reference the DATE variable with ${DATE} and not $DATE otherwise your command will not execute correctly !

# Mongodb admin cleanup
30 11 * * * BDIR=/home/backupuser/backup/mongodb/admin;
LAST=$(find $BDIR -mindepth 1 -maxdepth 1 -type d -printf '\%f\n' | sort -nr | head -1);
find $BDIR -mindepth 1 -maxdepth 1 ! -name "$LAST" -type d -exec rm -rf {} +