Python MongoDB – Get Started

Python MongoDB Tutorial

Python requires a driver to connect to MongoDB. PyMongo is one such driver that helps us to connect to a MongoDB Database and perform operations on Databases, Collections, Documents, etc.

In this introductory tutorial to PyMongo, we will install PyMongo in our computer, and try to make a connection to the MongoDB instance already running in your computer.

Install PyMongo

To install PyMongo, use pip command. pip would be already installed when you have installed your Python.

Run the following pip command to install pymongo package.

python -m pip install pymongo

To verify if pymongo is installed successfully, create a python file and write the following import statement.

import pymongo

If there is no error when you run this python program, pymongo import is successful, meaning pymongo is installed successfully.

Connect to MongoDB from Python

To connect to a MongoDB instance, pymongo provides pymongo.MongoClient() class. You can pass the url of the MongoDB instance as shown in the following program.

Make sure that Mongo Daemon is up and running at the URL you specified.

import pymongo

myclient = pymongo.MongoClient("mongodb://localhost:27017/")

If the above pymongo example program runs successfully, then a connection is said to made to the mongodb instance.

If you provide a wrong mongodb instance url or if the mongodb instance is not up, you will receive pymongo.errors.ServerSelectionTimeoutError.

PyMongo Tutorials List

Now that we have learned to make a connection to MongoDB from Python program, following tutorials will help with the subsequent topics of PyMongo.


In this tutorial of Python Examples, we have installed pymongo using pip. Then we imported pymongo package in python program. Later, we created a Mongo Client to the Mongo Daemon running at the specified URL.