Python MongoDB Database Connectivity - How to connect MongoDB with Python

To connect Python application with MongoDB database, we need to have installed following things in our computer system.


In this topic, we are focused to connect python application to MongoDB. So, we assume that Python and MongoDB is already installed. 

Install PyMongo Driver for Python

PyMongo is the official Python driver for MongoDB. We can use pip which is a package manager and easiest way to install the driver. Execute the following command on a command line (Terminal).

$ python -m pip install pymongo

Python Script to Connect MongoDB Database

After installing driver, create Python script to connect with MongoDB. First, we need to import MongoClient module to connect with database.

# Import pymongo driver
from pymongo import MongoClient
# Connect to MongoDB
client = MongoClient('localhost', port=27017)
# Create database
db =
# Create collection
collection = db.emp
# Create data to insert
record = {
'empid': 'E20021', 
'empName': 'Rohan', 
'profile': 'Admin'
# Insert data into collection
# Access inserted data

Run the Python Script

To test the script and database connectivity, we can execute the script from terminal by using the below command. 

$ python

After successful connectivity, It returns the inserted record. See the below screenshot.


We can cross verify whether data is inserted into the database by accessing the MongoDB from terminal. Use the mongo command.

$ mongo


Access Database

To Access database in the MongoDB, use the below command into the terminal.

> show dbs

It will list out all the available databases in the MongoDB. To access specific database, we can use use database_name command.


Access Table

To Access table / collection, use the below command into the terminal.

> show collections

The above command will list out all the available table/collection in the selected database.


Access Data

MongoDB stores data in documents. Documents are not like Microsoft Word or Adode PDF documents but rather JSON documents based on the JSON specification.

To access data from collection, use the following command into the terminal.

> db.emp.find()

See, it displays the data that we inserted using the Python script.


In this tutorial, we learnt how to connect to MongoDB database using Python Script. We can use this script to connect our Python application or just to test the database connection.

In next chapters, we will discuss about the database handling and more advanced topics. Till then Happy Coding!