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.
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.
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.
- PyMongo – Create Database – Tutorial on creating a MongoDB Database.
- PyMongo – Create Collection – Tutorial on creating a Collection in MongoDB Database.
- PyMongo – Insert Document – Tutorial on inserting a document to MongoDB Collection.
- PyMongo – Delete Documents – Tutorial on deleting document from MongoDB Collection.
- PyMongo – List Databases – Tutorial on listing Databases present in MongoDB.
- PyMongo – List Collections – Tutorial on listing Collections present in a Database.
- PyMongo – Delete or Drop Collection – Tutorial on deleting a collection from Database.
- PyMongo – Delete Database – Tutorial on deleting a database from MongoDB
- PyMongo – Solve pymongo.errors.ServerSelectionTimeoutError
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.