How to Import a Mongo database from a cloud server to your local machine in 2 minutes
This short article helps you import/clone/copy a mongo database sitting on a cloud server i.e AWS, Digital Ocean, or other onto your local when you need data to test without having to create datasets manually.
STEP 1
Open your terminal application on your local machine
Ssh into your cloud server using this command:
ssh -fN -L 27018:localhost:27017 <ubuntu@ip or root@ip of the server>
This creates a tunnel to the remote mongo database server and tunnels it through port 27117 to the local machine
In the instance you find the port is already in use, you can append the port to 27019 or you can free it using the following commands:
lsof -wni tcp:27018
Kill the process using the PID:
kill -9 <PID>
STEP 2
Now that we have mapped our remote server database to our local server port 27018. Next, we can copy from the remote server to our destination server using MongoDB’s mongodump/mongorestore pipeline using this command:
mongodump — port 27018 — db <remote db name> — archive | mongorestore <local destination db name> — archive
To understand the *mongodump* and *mongorestore* commands, read more on these links:
https://docs.mongodb.com/manual/reference/program/mongodump
https://docs.mongodb.com/manual/reference/program/mongorestore
STEP 3
Now we check the database on our local:
Use this command to initiate the mongo shell:
mongosh
Check all databases on the local machine:
show dbs
We should be able to see our copied database on the list of on our local machine
Here is a screenshot of the whole operation for reference :
You should be able to see the **hashnode_example **database on the list