Mongo DB export and import databases

1 min read

There are two command you need to use to backup MongoDB databases:

Backup lifecycle:

  1. Create a copy of database (export) as a backup
  2. Get it from the server
  3. Put archive back to the server
  4. Apply (import) target backup

Export database

Export db notes to folder /tmp/notes.

mongodump -d notes -o /tmp/notes

Import database

Add key drop if there can be key conflicts

mongorestore /tmp/notes --db notes [--drop]

Download backup from remote server

Create archive with folder /tmp/notes

tar -cvjf notes.tar.bz2 /tmp/notes

Then copy this archive to your computer via scp utility.

scp [email protected]:/root/notes.tar.bz2 ./

Upload backup to server of docker container

Upload it to server via scp:

scp ./notes.tar.bz2 [email protected]:/tmp

Or put it into your database docker container localserver_db_1

docker cp ./notes.tar.bz2 localserver_db_1:/tmp

Unpack the archive on your server (container)

mkdir /tmp/notes tar -xvjf /tmp/notes.tar.bz2 -C /tmp/

If you see an error

$ tar -xvjf notes.tar.bz2 tar (child): bzip2: Cannot exec: No such file or directory tar (child): Error is not recoverable: exiting now tar: Child returned status 2 tar: Error is not recoverable: exiting now

Then install bzip2 package

apt install bzip2