How can I connect Python Application Connection to MongoDB

Python Application Connection to MongoDB

MongoDB is one of the most popular NoSQL databases, which allows developers to easily work with the stored data. This tutorial provides an example of connection to the MongoDB server from the Python application.

1. In our case we have an environment with Python and MongoDB containers inside (can create such one at any time), but this instruction is suitable for the remote servers as well.
        
2. Connect the compute node via Cloudjiffy SSH Gate.
     

3. Install a MongoDB driver for Python using the command below:

pip install pymongo
       

4. Set up a simple script to check the DB server connection. For that use any preferable text editor and create a file with the .py extension (e.g. vim script.py).

1
2
3
4
5
6
7
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()

Just adjust the connection string with a relevant date, which can be gained from email for your MongoDB node:

  • {user} - username to log into database with
  • {password} - password for the appropriate user
  • {host} - link to the MongoDB container
  • {port} - port to be used for connection (use the default one - 27017)
  • {database} - database to be accessed (e.g. the default admin one)
     

This script will connect to the specified database server and will try to get its status. If any error occurs in the process, its description will be printed; otherwise, just a “You are connected!” string will be displayed.

5. So, execute code in the file by running the appropriate command:

python script.py

                                   
    

The “You are connected!” string ensures, that application was able to connect the DB server successfully, so you can start managing database node by extending code with other operations.

 


Was this article helpful?

mood_bad Dislike 0
mood Like 0
visibility Views: 12785