Python Connection to MongoDB

Python Application Connection to MongoDB

This guide shows how to connect a Python application to MongoDB on the platform. The workflow covers preparing a Python and MongoDB environment, connecting to the Python node through SSH, installing PyMongo, creating a simple connection test script, and verifying access to the MongoDB server.

Prepare the Environment

The source example uses an environment with both Python and MongoDB containers. The same instruction is also suitable when the Python application and MongoDB server are remote from each other.

Python MongoDB environment
Create an environment containing Python and MongoDB containers.

Connect to the Python Node through SSH

Connect to the Python compute node through the platform SSH Gate.

SSH Gate access
Connect to the Python compute node through SSH Gate.

Install the MongoDB Driver for Python

Install PyMongo, the MongoDB driver for Python:

pip install pymongo
Install PyMongo
Install the MongoDB Python driver using pip.

Create a MongoDB Connection Script

Create a Python file with a .py extension, for example script.py, and add the following connection test:

from pymongo import MongoClient
client = MongoClient("mongodb://{user}:{password}@{host}:{port}")
db = client.{database}
try: db.command("serverStatus")
except Exception as e: print(e)
else: print("You are connected!")
client.close()
{user}Username used to log in to MongoDB.
{password}Password for the selected MongoDB user.
{host}Hostname or link of the MongoDB container.
{port}MongoDB connection port. The source uses the default 27017.
{database}Database to access, for example the default admin database.

The required MongoDB connection details can be taken from the email sent for the MongoDB node.

MongoDB Python connection script
Create the Python connection script using the MongoDB connection values.

Run and Verify the Connection

Execute the Python script:

python script.py
Run MongoDB Python connection script
Run the script and verify the successful MongoDB connection message.

If the connection succeeds, the terminal displays You are connected!. If an error occurs, the script prints the exception description. After a successful test, extend the code with the MongoDB operations required by the application.

Expected Result

PyMongo is installed on the Python node, the application connects to MongoDB using the configured credentials and host information, successfully requests serverStatus, prints the successful connection message, and closes the client connection.

Important Notes

  • The Python and MongoDB containers can be in the same environment or on remote servers.
  • The documented Python driver is pymongo.
  • The source uses the default MongoDB port 27017.
  • Connection values are available in the email for the MongoDB node.
  • The test uses db.command("serverStatus") to verify connectivity.
  • Close the client with client.close() after use.