HowTo: Connect to a Remote MongoDB Database using PyCharm

In my last blog, I detailed the steps for installing MongoDB 3.4 on RHEL7, you can view that post by clicking the button below.

The default IP and port in the MongoDB setting are 127.0.0.1:27017 which allows access only from the localhost MongoDB is installed on. If you would like to access a remote MongoDB database, there are some configuration changes you would need to complete.

CREATE A USER:

Connect to the MongoDB host server and access the mongo shell:

mongod

Before creating any regular users, you should create an admin user using the default Admin Database created during MongoDB installation:

The root role grants permissions that span the readWriteAnyDatabase, dbAdminAnyDatabase, userAdminAnyDatabase, clusterAdmin restore, and backup roles combined. You can choose to grant any of the roles individually rather than granting root.

After creating your privileged Admin user, you will need to create the user with read and write permissions on the chosen database:

Connect to the database you want to grant the user permissions on and create the user:

Allow Access to MongoDB from other IPs via Database Authorizations:

Open MongoDB access to specific IPs

Find the public IP of the host:

Edit the MongoDB config file as sudo:

vi /etc/mongod.conf

Search for the network interfaces line, it has a parameter bindip that restricts access to MongoDB from the localhost only. 

To allow specific IPs - such as the public IP of the MongoDB server - for anyone that would connect via VPN to the environment:

Then uncomment the security access via authentication line:

When Authorization is enabled, all subsequent connections would have to be from authorized users.

Restart the mongod service:

sudo service mongod restart

Open Port 27017 to inbound connections:

iptables -A INPUT -p tcp --dport 27017 -j ACCEPT

*Note: If you don't want to specify an IP, but would rather allow all IPs to connect to the MongoDB database, comment the BindIP line, but make sure you enable security authorizations, otherwise, anyone anywhere will be able to connect to the MongoDB database.

Connect Remotely Using PyCharm:

On your local computer with the PyCharm application or any other python IDE, import the pymongo module to utilize the MongoClient tool, enter your database connection details and you're all done!

Connect via MONGO shell:

SSH to the MongoDB host server or connect via your VPN.

On the terminal, run:

mongo -u Harry -p Hogwarts4ever 192.168.0.1/admin

CONNECT VIA PYTHON SHELL:

SSH to the remote host or connect via your VPN.

Launch a python shell and run the same commands that you would run using PyCharm:

 

*Cover images from mongodb.org