Skip to main content

MongoDB on Ubuntu!

SSH Config

To avoid entering your username and password each time, consider adding the following information to your ssh config file, typically located at ~/.ssh/config

Assuming you have an account on the VM and have created and set your SSH key, the following code presumes your SSH key is named myvm.

Host <your-host-ip>
HostName <your-host-ip>
User <your-username>
IdentityFile ~/.ssh/myvm
info

Just in case if there is a gateway (Jump host), use following in the config file:

ProxyJump <your-username>@your-gateway-ip

tip

To add key to ssh, use:

ssh-add -k ~/.ssh/myvm

Now, create a tunnel to the mongodb host machine

ssh -4 -L 27017:localhost:27017 your-mongodb-host-ip
info

To make MongoDB work on localhost, a tunnel is required, typically on port 27017. The use of -4 specifies that the tunnel should be established over IPv4.

Now MongoDB Compass can be used to access the MongoDB by connecting it to localhost:27017

Writing Python code to interact with MongoDB

from pymongo import MongoClient
mongoURL = "mongodb://localhost:27017/"

try:
conn = MongoClient(mongoURL)
mydb = conn["your-db-name"]
txs_col = mydb["your-collection-name"]
print("Connected successfully!!!")
except:
print("Could not connect to MongoDB")