MongoDB Python Connection

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 your Pythonapplication.

1. In our case we have an environment with Python and MongoDB containers inside (you can createsuch one at any time), but this instruction is suitable for the remote servers as well.
        
2. Connect your compute node via Apiqcloud 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).

?
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 your 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.

 
  • MongoDB Python Connection
  • 0 Usuários acharam útil
Esta resposta lhe foi útil?

Artigos Relacionados

Deploy Python Project Via Archive URL

Upload and Deploy Your Python Application With Apiqcloud you can easily upload and deploy any...

Deploy Python Project Via GIT SVN

Deploy Python Project via GIT/SVN You can host any public or your private Python project at...

How to Deploy Django App to Apiqcloud Cloud

 Django CMS is a free open-source content management system based on the Django web...

MySQL Python Connection

Python Application Connection to MySQL MySQL is a highly popular open source database, used by...