mongodump is a utility provided by mongodb for creating database backups. This is a very useful utility that can be considered for taking backups of live server databases very efficiently. For database restore, you need to use the mongorestore command.
1. Back up mongodb database (mongodump)
There are many ways to back up MongoDB database. Use the mongodump command to back up all databases, a single collection, or a single database.
Back up a single database
Use this command to back up only a single database (named mydb). The backup will be created in the /backup/db/ directory.
$ mongodump --db mydb --out / backup / db /
-db - The name of the database to be backed up
-out - The database backup location. This will create a folder with the name of the database.
You can specify the host, port, username and password for remote database connection backup, as shown below.
$ mongodump --host 10.0.1.7 --port 27017 --username admin --password somepassword --db mydb --out / backup / db /
Back up all databases
To back up all databases, just run the following command. Here /data/db/ is the location of your mongodb data directory and /backup/db is the location of the backup directory.
$ mongodump --out / backup / db /
You can specify the host and port for the remote database.
Backup a single collection
This command will back up a single collection from the database. The backup file will be created in the dump/mydb/ directory.
$ mongodump --collection mycollection --db mydb --out / backup / db /
2. Use mongorestore to restore MongoDB database
mongorestore is a command line tool used to restore mongodb database backup. Here /data/db/ is the location of your mongodb data directory and /backup/db is the location of the backup directory.
$ mongorestore --db mydb --drop / backup / db / mydb
-drop - Will drop the database if it already exists.
Simply move the backup file to the remote server and run the same command there to restore the backup.
3. MongoDB Backup Shell Script
The following script can be easily scheduled in the scheduler to back up the database regularly. Create the following file
$ vi /backup/mongo-backup.sh
Add the following content to the file. Update the database hostname, database name, username and password accordingly.
#!/bin/sh TODAY=`date +%d%b%Y` BACKUP_DIR=/backup/db mkdir -p ${BACKUP_DIR}/${TODAY} mongodump -h <DATABASE_HOST> -d <DATABASE_NAME> -u <USERNAME> -p <PASSWRD> --out ${BACKUP_DIR}/${TODAY}/
Now configure it in crontab to run every day.
0 2 * * * /backup/mongo-backup.sh
This article has ended here. For more exciting content, you can pay attention to the MySQL Video Tutorial column on the PHP Chinese website!
The above is the detailed content of How to backup, restore and migrate MongoDB databases. For more information, please follow other related articles on the PHP Chinese website!