How to connect MongoDB with Python?

python MongoDB

If you are looking to integrate Python with MongoDB, this tutorial is for you. This guide will cover the fundamentals of MongoDB and its integration with Python. Whether you’re a beginner or an experienced developer, you’ll find this guide useful.

Introduction to MongoDB

MongoDB is a popular document-oriented database management system that allows you to store data in JSON-like documents. It’s a NoSQL database, meaning that it doesn’t use tables or rows like traditional relational databases. Instead, it stores data as collections of documents. MongoDB is widely used for big data, real-time analytics, and web applications.

Installing MongoDB

Before we get started with PyMongo, we need to install MongoDB on our machine. You can download the MongoDB Community Server from the official website and follow the installation guide. Once you’ve installed MongoDB, you can start the server by running the following command:


Getting Started with PyMongo

PyMongo is a Python library for MongoDB that allows you to interact with MongoDB databases using Python. You can install PyMongo using pip, the Python package installer:

pip install pymongo

Creating a Connection

To connect MongoDB with Python, using PyMongo, you need to create a MongoClient object:

from pymongo import MongoClient

client = MongoClient()

This will connect to the default MongoDB instance running on your machine. If you want to connect to a different instance or provide connection parameters, you can pass them as arguments to the MongoClient constructor.

Creating a Database

To create a database in MongoDB, you can simply use the client object and specify the name of the database:

db = client['mydatabase']

Creating a Collection

Collections are similar to tables in relational databases. To create a collection in MongoDB, you can simply use the database object and specify the name of the collection:

collection = db['mycollection']

Inserting Data

To insert data into a collection, you can use the insert_one() or insert_many() method:

document = {'name': 'John Doe', 'age': 25}
result = collection.insert_one(document)

This will insert a single document into the collection. If you want to insert multiple documents, you can use the insert_many() method:

documents = [{'name': 'John Doe', 'age': 25}, {'name': 'Jane Doe', 'age': 30}]
result = collection.insert_many(documents)

Retrieving Data

To retrieve data from a collection, you can use the find() method:

cursor = collection.find()
for document in cursor:

This will retrieve all the documents in the collection. You can also use the find_one() method to retrieve a single document:

document = collection.find_one({'name': 'John Doe'})

Updating Data

To update data in a collection, you can use the update_one() or update_many() method:

result = collection.update_one({'name': 'John Doe'}, {'$set': {'age': 26}})

This will update the age of the document with the name ‘John Doe’ to 26. If you want to update multiple documents, you can use the update_many() method:

result = collection.update_many({'name': 'John Doe'}, {'$set': {'age': 26}})

Deleting Data

To delete data from a collection, you can use the delete_one() or delete_many() method:

result = collection.delete_one({'name': 'John Doe'})

This will delete the document with the name ‘John Doe’. If you want to delete multiple documents, you can use the delete_many() method:

result = collection.delete_many({'name': 'John Doe'})

Querying Data

MongoDB provides a rich query language that allows you to query documents based on specific criteria. You can use operators like $eq, $ne, $gt, $lt, $gte, and $lte to query data. Here’s an example:

cursor = collection.find({'age': {'$gt': 25}})
for document in cursor:

This will retrieve all the documents in the collection where the age is greater than 25.

Aggregation Framework

The MongoDB Aggregation Framework provides a powerful way to analyze data in a collection and return computed results. You can use the aggregation pipeline to perform various operations on data, such as grouping, sorting, and filtering. Here’s an example:

pipeline = [
    {'$match': {'age': {'$gt': 25}}},
    {'$group': {'_id': '$name', 'count': {'$sum': 1}}},
    {'$sort': {'count': -1}}
cursor = collection.aggregate(pipeline)
for document in cursor:

This will group the documents by name and count the number of documents where the age is greater than 25, and then sort the results by the count in descending order.


Indexes in MongoDB are similar to indexes in traditional relational databases. They allow you to improve the performance of queries by reducing the number of documents that need to be scanned. You can create indexes on one or more fields in a collection. Here’s an example:

collection.create_index([('name', 1)])

This will create an ascending index on the name field in the collection.


In this tutorial, we connect Mongodb with python using PyMongo. We learned how to create a connection, create a database and collection, insert, retrieve, update, and delete data, query data using operators and the aggregation framework, and create indexes.

Follow Us on

Read More

Thank You

Related Post

Leave a Reply

Your email address will not be published. Required fields are marked *