MongoDB is a popular NoSQL database that allows you to store your data in the form of documents that consist of key-value pairs. System administrators need to regularly backup their MongoDB databases to be able to recover quickly in case of data loss. But sometimes you may also need to restore MongoDB dump to recover your data. In this article, we will learn how to restore MongoDB dump in Windows & Linux.
How to Restore MongoDB Dump in Windows & Linux
You can backup one or more your MongoDB databases using mongodump command. Here is the command to backup specific database.
$ mongodump --db databasename
For example, if you want to backup database test_db, you can run the following command.
$ mongodump --db test_db
If you want to limit the amount of data exported, then instead of backing up the entire database, you can choose to export only collections, which are subsets of a database. For example, here is the command to backup collection myCollection in database test_db.
$ mongodump --collection myCollection --db test_db
When you use mongodump command it will create a backup file in backup data directory. The MongoDB dump files have .dump extension.
Restore MongoDB dump
If you want to restore MongoDB data dump, you can do so using mongorestore command. If you want to restore a MongoDB dump file to its original database, here is the command syntax.
$ mongorestore --verbose \path\dump
Here is an example to restore Mongodump file at /home/ubuntu.
$ mongorestore --verbose /home/ubuntu/test_db.dump
Alternatively, you can also use the –archive option.
$ mongorestore --archive=/home/ubuntu/test_db.dump
If your MongoDB dump file has been gzipped, you can also use –gzip option.
$ mongorestore --gzip --archive=/home/ubuntu/test_db.dump
If you want to restore MongoDB dump file to a new database, here is the command syntax for it.
$ mongorestore --db databasename --verbose \path\dump\<dumpfolder>
Here is an example to restore MongoDB dump file of test_db database to another database db3.
$ mongorestore --db db3 --verbose /home/ubuntu/test_db.dump
In this article, we have learnt how to restore MongoDB database from its dump file. The commands and their syntax are the same in both Windows & Linux. The only difference is that the path to dump file will consist of back slashes in Windows, and forward slashes in Linux.
It is important to regularly backup MongoDB databases to be able to restore it whenever there is data loss or other issues. You can run the above commands in terminal or even add it to a shell script (Linux) or powershell script (Windows).