Now that we installed MongoDB on our device, let’s connect MongoDB with Python.

Connect MongoDB with Python:

We’ll use PyMongo to create, connect and manipulate databases using Python. PyMango is the official python driver provided by MongoDB and is the recommended way to work with MongoDB from Python.

Setup Pymango:

Now, let’s install PyMongo using pip.

Run the below command in your command line in general python installation or in your created virtual environment.

pip install pymongo


Collecting pymongo

  Downloading pymongo-3.12.1-cp38-cp38-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (527 kB)

     |████████████████████████████████| 527 kB 553 kB/s 

Installing collected packages: pymongo
Successfully installed pymongo-3.12.1

pyMongo is now installed in your system.

Importing MongoClient from PyMongo:

To use installed Pymongo with Python we have to import it. Let’s import MongoClient from PyMongo.

from pymongo import MongoClient

Establishing connection:

We need to create aMongoClient instance in order to establish the connection between MongoDB and Python.

Let’s create our object as mclient for our active MongoDB instance.

mclient = MongoClient()
  • MongoClient() takes the following arguments
  • host (optional)– This is the name of the host on which the server is running. 
  • port(optional)– This is the port number we wanted to connect.
  • username – This is the name of the user while setting up the database server. 
  • password – Password that is set while creating a user. 

To use localhost as host and 27017 as a port (default port), we write the following code:

mclient = MongoClient(host="localhost", port=27017)

It can also be written using MongoDB URL format as:

mclient = MongoClient("mongodb://localhost:27017")

Verify Connection:

To check whether the connection is successful or not we’ll write a simple program importing MongoClient from PyMongo and ConnectionFailure from PyMango’s error package.

from pymongo import MongoClient

from pymongo.errors import ConnectionFailure

mclient = MongoClient()



   print("Connection Successful")

except ConnectionFailure:

   print("Server not available")

We imported ConnectionFailure from pymongo’s error library to detect any exceptions.


Connection Successful

Closing connection:

After completion of our work, we will close the connection by:


Additional Resources:

Happy Learning 🙂