Javaexercise.com

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.

Prerequisite

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. 

mongoconnect.py

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

Run the Python Script

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

$ python mongoconnect.py

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

python-mongodb-connectivity

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

$ mongo
python-mongodb-connectivity

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.

python-mongodb-connectivity

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.

python-mongodb-connectivity

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()
python-mongodb-connectivity

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


Conclusion

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!