Last modified: Mar 25, 2025 By Alexander Williams
How to Install PyMongo in Python Step by Step
PyMongo is the official MongoDB driver for Python. It allows you to interact with MongoDB databases easily. This guide will help you install PyMongo step by step.
Prerequisites
Before installing PyMongo, ensure you have Python installed. You can check this by running python --version
in your terminal.
python --version
Python 3.9.0
If Python is not installed, download it from the official website. Also, ensure you have pip, Python's package manager.
Install PyMongo Using pip
The easiest way to install PyMongo is using pip. Open your terminal or command prompt and run the following command.
pip install pymongo
Successfully installed pymongo-4.3.3
This will install the latest version of PyMongo. If you encounter a ModuleNotFoundError, refer to our guide on How To Solve ModuleNotFoundError: No module named in Python.
Verify the Installation
After installation, verify PyMongo is installed correctly. Open a Python shell and import PyMongo.
import pymongo
print(pymongo.__version__)
4.3.3
If you see the version number, PyMongo is installed successfully.
Install a Specific Version of PyMongo
Sometimes, you may need a specific version of PyMongo. Use the following command to install a particular version.
pip install pymongo==4.2.0
Successfully installed pymongo-4.2.0
This ensures compatibility with your project requirements.
Upgrade PyMongo
To upgrade PyMongo to the latest version, use the following command.
pip install --upgrade pymongo
This will fetch and install the latest stable release.
Install PyMongo in a Virtual Environment
It's good practice to use a virtual environment. This keeps your project dependencies isolated.
First, create a virtual environment.
python -m venv myenv
Activate the virtual environment.
source myenv/bin/activate # Linux/Mac
myenv\Scripts\activate # Windows
Now, install PyMongo inside the virtual environment.
pip install pymongo
Connect to MongoDB Using PyMongo
Once installed, you can connect to a MongoDB database. Here's a simple example.
from pymongo import MongoClient
# Connect to MongoDB
client = MongoClient("mongodb://localhost:27017/")
# List all databases
print(client.list_database_names())
['admin', 'local', 'test']
This confirms your connection to MongoDB is working.
Conclusion
Installing PyMongo is straightforward with pip. Always verify the installation and consider using a virtual environment. Now you're ready to work with MongoDB in Python.
If you face any issues, check our guide on How To Solve ModuleNotFoundError: No module named in Python for troubleshooting.