How to connect MongoDB to Python

Hello Programmer. In this Python tutorial, we will be working on MongoDB database connection with Python. In easy words, we will learn how to connect MongoDB with Python program.

To make things simple we will go step by step from connecting MongoDB to python to writing python program using MongoDB. Before starting with the connection of MongoDB you need to check out its installation process.

How to install MongoDB in Python

Once you have successfully installed the MongoDB using python we can proceed further with its connection.

Connect MongoDB in Python

Firstly we must have MongoDB installed in the system using the pip. The installation process is quite simple and we have covered it in our previous tutorial.

Connecting MongoDB to Python is quite simple as shown below.

from pymongo import MongoClient

In this import statement, we are importing the MongoClient class from the pymongo package.

We can check the connection by creating a reference to the MongoClient as follows.

from pymongo import MongoClient

mongo = MongoClient()
print(mongo)

Output:

MongoClient(host=['localhost:27017'], document_class=dict, tz_aware=False, connect=True)

This ensures that the connection has been made between the MongoClient and the Python.

The localhost is the hostname and 27017 is the port number on which MongoDB client is installed.

The MongoClient takes two parameters, the first parameter is the hostname or IP address and the second parameter is the port number.

mongo = MongoClient('localhost', 27017)

This can also be written as.

mongo = MongoClient('mongodb://localhost:27017')

Here the parameters pass to MongoClient are as follows:

  • mongo is protocol.
  • localhost is the hostname or can consist of an IP address.
  • 27017 is the port number.

The Output will remain the same which is as follow.

MongoClient(host=['localhost:27017'], document_class=dict, tz_aware=False, connect=True)

 

Leave a Reply

Your email address will not be published. Required fields are marked *