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.

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

Install the MongoDB Driver for Python
Install PyMongo, the MongoDB driver for Python:
pip install pymongo

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()
27017.admin database.The required MongoDB connection details can be taken from the email sent for the MongoDB node.

Run and Verify the Connection
Execute the Python script:
python script.py

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.
