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 your Python application.
1. In our case we have an environment with Python and MongoDB containers inside (you can create such one at any time), but this instruction is suitable for the remote servers as well.
2. Connect your compute node via CirrusGrid SSH Gate.
3. Install a MongoDB driver for Python using the command below:
pip install pymongo
4. Set up a simple script to check your DB server connection. For that use any preferable text editor and create a file with the .py extension (e.g. vim script.py).
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:
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.
Powered by BetterDocs
Necessary cookies are absolutely essential for the website to function properly. This category only includes cookies that ensures basic functionalities and security features of the website. These cookies do not store any personal information.
Any cookies that may not be particularly necessary for the website to function and is used specifically to collect user personal data via analytics, ads, other embedded contents are termed as non-necessary cookies. It is mandatory to procure user consent prior to running these cookies on your website.