MongoDB

Learn how to created automated backups of your MongoDB databases to be stored on Filebase.

What is MongoDB?

MongoDB is a cross platform database program that uses JSON-like documents. MongoDB is open source and free to download and self-host on any server.

Read below to learn how to set up automated backups of your MongoDB databases to be stored in a Filebase bucket.

Prerequisites:

This guide was written using Ubuntu 20.04. Commands and workflow may vary depending on your operating system.

1. Copy the following script onto your server and save it as mongodb_backup.sh.

Edit the values to reflect your local configuration.

#!/bin/bash

# Your User’s home directory
export HOME=/home/filebase/

# Your server's hostname
HOST=localhost

# Your database name to be backed up
DBNAME=database-name

# S3 bucket name
BUCKET=filebase-sample-bucket

# Linux user account
USER=filebase

# Current time
TIME=`/bin/date +%d-%m-%Y-%T`

# Backup directory
DEST=/home/$USER/tmp

# Tar file of backup directory
TAR=$DEST/../$TIME.tar

# Create backup dir (-p to avoid warning if it already exists)
/bin/mkdir -p $DEST

# Log
echo "Backing up $HOST/$DBNAME to s3://$BUCKET/ on $TIME";

# Dump from mongodb host into backup directory
/usr/bin/mongodump -h $HOST -d $DBNAME -o $DEST

# Create tar of backup directory
/bin/tar cvf $TAR -C $DEST .

# Upload tar to s3
/usr/bin/aws --endpoint https://s3.filebase.com s3 cp $TAR s3://$BUCKET/ --storage-class STANDARD_IA

# Remove tar file locally
/bin/rm -f $TAR

# Remove backup directory
/bin/rm -rf $DEST

# Confirm success
echo "Backup of MongoDB databases to Filebase bucket $BUCKET completed successfully. "

This script uses the mongodbdump function to create a backup dump of all MongoDB databases and stores it to a tar file that is then uploaded to Filebase using an AWS CLI command.

2. Run the script to test that your configuration works as expected.

It should return the following output:

In your Filebase bucket, you should see the tar file uploaded:

3. Set up automation of this script using a cronjob.

Open your crontab with the following command:

crontab -e

4. Add the following line to your crontab to create a cronjob that runs your mongodb_backup.sh script:

0 8 * * * /path/to/mongodb_backup.sh

Replace the file path with the correct path for your configuration.

This cronjob is scheduled to run every day at 8:00AM on your server. Configure the cronjob values to reflect your desired configuration.

You’ve now configured automated backups for your MongoDB databases!

If you have any questions, please join our Discord server, or send us an email at hello@filebase.com

Last updated