Install Python MongoDB Driver PyMongo on Ubuntu/CentOS 7/Windows

MongoDB and Python make a powerful combination    for rapid development of scalable applications. MongoDB is fast and scalable in storing, and also flexible in querying data. For the modern Web and mobile applications, MongoDB NoSQL database is likely a better fit than traditional relational database management system.

In order to be able to connect to MongoDB with Python, you need to install the Python MongoDB driver package also called the PyMongo driver.

In this tutorial we will learn how to install PyMongo driver on Linux(Ubuntu 16.04/CentOS 7) and Microsoft Windows.

Install PyMongo on Ubuntu Linux

In Ubuntu Two different PyMongo packages available for Python version 3 and version 2.

For Python3, install the python3-pymongo package:

sudo apt-get install python3-pymongo

For Python 2:

sudo apt-get install python-pymongo

To test pymongo driver on Ubuntu, execute the command:

python3 -c "import pymongo"

IF Python did not raise an ImportError, Then the driver is installed correctly.

Install PyMongo on CentOS 7

The epel repository provides PyMongo on CentOS 7 (For both versions 2 and 3).

First enable the epel repository:

yum -y install epel-release

Install python-pymongo package for Python 2:

yum -y install python-pymongo

For Python 3, we need to install pip command, then mongodb driver using the pip command:

yum -y install python34-pip
pip3 install pymongo

Install PyMongo Driver on Windows 10/Server 2016

On windows we install MongoDB driver using the pip command, Open the windows command prompt and execute:

pip install pymongo

(The pip command is available from the windows Python 3 package by default.)

Example: connect to MongoDB Server in Python

To test the database connection, add following code to your python script and execute. The program will print the list of the names of all databases on the local server.

#!/usr/bin/python3

from pymongo import MongoClient

client = MongoClient()
print(client.database_names())
client.close()

The Python MongoClient object provides the functionality to connect to the MongoDB and access NoSQL database server.