Backup and Restore Mongo Databases

Complete guide of how to backup and restore a database or a collection from mongodb

Gaurav Mehla
_devblogs
Published in
3 min readJan 26, 2018

--

MongoDB is one of the most popular databases we have right now. It is currently been used with a lot of projects. As the usage increases, we start facing issues like taking backup and restoring it. So today, we will learn which tool to use for backup and restore & how to use them.

In this tutorial, we will take hot backup. i.e You can connect to a running instance of MongoDB and take a backup even when users are using the database.

Prerequisites

  • Make sure you have installed MongoDB and it is running.

⚠️ Click Here if you don’t know how to install MongoDB

MongoDB version I am using

Tools we will use

⚜️ The list

  1. Backup a Whole database
  2. Backup a Single collections
  3. Restore Whole database
  4. Restore Single collection

⚜️ Backup Section

Backup a Whole Database

mongodump -d devdb -o mongoBackups

devdb is the name of the database and mongoBackups is the directory in which I want to dump the database

Backup a Single Collection

mongodump -d devdb -o mongoBackups --collection vehicles

devdb is the name of the database and mongoBackups is the directory in which I want to dump the database and vehicles is the name of the collection which I want to backup.

⚜️ Restore Section

Restore Whole Database

mongorestore -d devdb mongoBackups/devdb

devdb is the name of the database into which we will restore data and mongoBackups is the directory in which we dumped the database devdb

Restore Single Collection

mongorestore -d devdb -c vehicles devdb/devdb/vehicles.bson

devdb is the name of the database into which we will restore data and vehicles is the name of the collection & then the path of the .bson file.

🔅 If you have collection in .json then mongorestore will through an error. In that case, you have to use mongoimport i.e :

mongoimport --db devdb --collection vehicles --file vehicles.json --jsonArray

That’s it!!

Happy Coding !!

🎧 Listening to “Two Steps from Hell — Heart of Courage”, Focus… Focus.. & just Focus… Must listen.

If you like this article, please give it some claps 👏 and share it! If you do not like this post or have any type of questions regarding anything that i mentioned in this post. Feel free to ask me. Just post an issue in my “Ask Me Anything” by clicking here.

For more like this, follow me on Medium or Twitter. To ask a Question visit this link. More about me on my website.

--

--

Gaurav Mehla
_devblogs

Software engineer & Web hacker. Spent 30+% of life on playing with JS