Introduction :
I was looking for an easy way to dump and restore MongoDB data from my cloud.mongodb cluster free tier plan. Actually, I am running a couple of side projects on cloud.mongodb and the free plan is enough for the current traffic.
Using mongodump and mongorestore, we can dump and restore MongoDB data from a cloud host. We can do that from the command line easily with just a line but a lazy developer like me always tries to get anything right out of the box. So, I searched for a GitHub solution and luckily I found one. That is what I am going to talk today. This is an open sourced project and it helped me a lot to quickly dump and restore a MongoDB from cloud.mongodb.
Setup :
This project is called mongodb-database-backup and you can download or clone it from here on Github. We will install it using npm
- Create one blank npm project like :
npm i my_project
- Add mongodb-database-backup to this project :
npm i mongodb-atlas-backup
- Install esm :
npm i esm
- Change the scripts tab in package.json file as below :
"scripts": {
"start": "node -r esm index.js"
}
- Create one index.js with the below code :
import MongoBackup from 'mongodb-atlas-backup'
// Create an instance of the database connection
const backup = new MongoBackup({
user: 'admin',
password: 'fdsfdsew%FczKs7@UE6',
replicaSet: 'Cluster0-shard-0',
nodes: [
'cluster0-shard-00-00-eqqwe.mongodb.net:27017',
'cluster0-shard-00-01-eqqwe.mongodb.net:27017',
'cluster0-shard-00-02-eqqwe.mongodb.net:27017'
]
})
// Dump your cluster
// backup.dump()
// Restore data to your cluster
backup.restore()
Here, change the user,password and replicaSet with your username, password and cluster name. Also, change the value of the nodes.
Uncomment the dump() code if you want to take a dump.
Use npm run start to use this script.