Course Outline (Part 23)

Node.js might be the most popular backend for building web APIs with MongoDB, but when it comes to Data Science, Machine Learning, and heavy automation, Python is the undisputed king.

Because MongoDB stores data as documents (which map perfectly to Python Dictionaries), the integration between the two is incredibly natural. In this module, we will learn how to use PyMongo, the official MongoDB driver for Python.


1. Installing PyMongo

To get started, you need to install the PyMongo package using pip.

Open your terminal and run:

pip install pymongo

(Note: If you are connecting to MongoDB Atlas, you also need to install the dnspython package so Python can resolve the mongodb+srv:// protocol. You can install both at once by running pip install pymongo[srv]).


2. Connecting to the Database

Connecting to MongoDB in Python requires importing the MongoClient class.

Create a file called app.py and write the following code:

from pymongo import MongoClient

# 1. Provide the Connection String
# Replace with your Atlas connection string if using the cloud!
uri = "mongodb://localhost:27017"

try:
    # 2. Create the Client
    client = MongoClient(uri)
    
    # 3. Access the Database and Collection
    db = client['library']
    collection = db['books']
    
    print("Successfully connected to MongoDB!")

except Exception as e:
    print(f"An error occurred: {e}")

Unlike Node.js, PyMongo operations are synchronous by default. You do not need to use await or deal with Promises. Python will automatically block the execution of the script until the database responds.


3. CRUD Operations in Python

The syntax for performing CRUD operations in PyMongo is almost exactly the same as the MongoDB Shell, but written using Python dictionaries and lists.

Create (Insert)

In PyMongo, the method names use Python’s “snake_case” naming convention instead of JavaScript’s “camelCase”. So insertOne becomes insert_one.

new_book = {
    "title": "The Martian",
    "author": "Andy Weir",
    "pages": 369,
    "tags": ["Sci-Fi", "Space", "Survival"]
}

# Insert the document
result = collection.insert_one(new_book)
print(f"Inserted document ID: {result.inserted_id}")

Read (Find)

The find() method returns a PyMongo Cursor object. You can easily iterate through this cursor using a standard Python for loop.

# Find all books that have the "Sci-Fi" tag
cursor = collection.find({"tags": "Sci-Fi"})

print("Sci-Fi Books:")
for book in cursor:
    # 'book' is a standard Python Dictionary
    print(f"- {book['title']} by {book['author']}")

Update

To update documents, use update_one or update_many. Remember to use the $set operator!

# Find "The Martian" and update its page count
filter_query = {"title": "The Martian"}
update_query = {"$set": {"pages": 370}}

result = collection.update_one(filter_query, update_query)
print(f"Modified {result.modified_count} document(s).")

Delete

To remove data, use delete_one or delete_many.

# Delete "The Martian"
result = collection.delete_one({"title": "The Martian"})
print(f"Deleted {result.deleted_count} document(s).")

4. Aggregations in Python

Just like in the shell, you can run complex aggregations in Python. You simply pass a list of dictionaries to the aggregate() method.

pipeline = [
    {"$match": {"pages": {"$gt": 300}}},
    {"$group": {"_id": "$author", "averagePages": {"$avg": "$pages"}}},
    {"$sort": {"averagePages": -1}}
]

results = collection.aggregate(pipeline)

for result in results:
    print(f"Author: {result['_id']}, Avg Pages: {result['averagePages']}")

5. Integrating with Pandas (Data Science)

The real magic of using Python with MongoDB is the ability to instantly pull database data into Pandas, the world’s most popular data analysis library.

A Pandas DataFrame is essentially a high-powered spreadsheet in Python. Because PyMongo returns data as dictionaries, converting MongoDB data into a DataFrame takes exactly one line of code.

import pandas as pd
from pymongo import MongoClient

client = MongoClient("mongodb://localhost:27017")
collection = client['ecommerce']['sales']

# 1. Query the database (e.g., get all sales from 2026)
cursor = collection.find({"year": 2026})

# 2. Convert the MongoDB Cursor directly into a Pandas DataFrame
df = pd.DataFrame(list(cursor))

# Now you have all the power of Pandas!
print(df.head()) # Print the first 5 rows
print(df.describe()) # Generate statistical summaries (mean, min, max)

# You can instantly plot this data using Matplotlib or export it to Excel:
# df.to_excel("sales_report.xlsx")

Summary

Python and MongoDB are a match made in heaven.

  • Use pip install pymongo to install the official driver.
  • The syntax is nearly identical to the shell, but uses snake_case (e.g., insert_one, update_many).
  • BSON Documents perfectly map to Python Dictionaries.
  • You can instantly load MongoDB queries into Pandas DataFrames for advanced machine learning, plotting, and statistical analysis.

We have now covered the two most popular programming languages for MongoDB. But what if you are managing a massive enterprise application that requires complex search capabilities? In Module 23, we will dive deeper into Atlas Search!

Discussion

Loading comments...