Course topics

By WebNest Studio Engineering Team

Python Tutorial

MongoDB with PyMongo

Not every database uses tables. MongoDB is a popular document database: it stores JSON-like documents in collections, and documents in the same collection can have different fields. This suits data with a flexible or nested shape — product catalogues, user profiles, event logs.

Python talks to MongoDB with the official PyMongo driver, and documents are simply Python dictionaries. This lesson covers connecting, inserting, querying with filters and projections, updating, deleting, indexes and the aggregation pipeline.

These examples need a MongoDB server (for example docker run -p 27017:27017 mongo:8) and pip install pymongo, so run them on your own computer.

Why it matters

Not all data fits neatly into tables. MongoDB stores documents that look like Python dictionaries and may differ from one another, which suits product catalogues, logs and content. It is the most widely used document database, and working with it from Python uses dictionaries for both the data and the queries.

Documents, Collections and Queries

A document is a dict; every document gets a unique _id (an ObjectId) unless you supply one. A collection groups documents, and a database groups collections — both are created automatically on first insert. Queries are dicts too: {"price": {"$gt": 100}} means price > 100. Common operators are $eq, $ne, $gt, $gte, $lt, $lte, $in, $and, $or and $regex. A projection such as {"_id": 0, "name": 1} chooses which fields to return.

Updates, Indexes and Aggregation

Updates use operators: $set changes fields, $inc adds to numbers, $push appends to arrays, $unset removes fields. upsert=True inserts when nothing matches. Indexes (create_index) make queries fast and can enforce uniqueness. The aggregation pipeline is a list of stages — $match, $group, $sort, $project, $lookup — similar to SQL's WHERE, GROUP BY, ORDER BY and JOIN.

Examples

Connect, insert and query documents

Python
# pip install pymongo
from pymongo import MongoClient, DESCENDING

client = MongoClient("mongodb://localhost:27017/")
db = client["shop"]
products = db["products"]
products.delete_many({})                         # start fresh for the demo

result = products.insert_one({"name": "Pen", "price": 20, "tags": ["stationery"]})
print("inserted id type:", type(result.inserted_id).__name__)

products.insert_many([
    {"name": "Headphones", "price": 1499, "tags": ["electronics", "audio"]},
    {"name": "Mouse", "price": 699, "tags": ["electronics"], "wireless": True},
    {"name": "Notebook", "price": 60, "tags": ["stationery"]},
])

print(products.find_one({"name": "Mouse"}, {"_id": 0}))
for doc in products.find({"price": {"$gt": 100}}, {"_id": 0, "name": 1, "price": 1}).sort("price", DESCENDING):
    print(doc)
print("electronics:", products.count_documents({"tags": "electronics"}))
Output
inserted id type: ObjectId
{'name': 'Mouse', 'price': 699, 'tags': ['electronics'], 'wireless': True}
{'name': 'Headphones', 'price': 1499}
{'name': 'Mouse', 'price': 699}
electronics: 2

Update, upsert and delete

Python
from pymongo import MongoClient

products = MongoClient("mongodb://localhost:27017/")["shop"]["products"]

res = products.update_one({"name": "Pen"}, {"$set": {"price": 25}, "$push": {"tags": "sale"}})
print("matched:", res.matched_count, "modified:", res.modified_count)

res = products.update_many({"tags": "electronics"}, {"$inc": {"price": -100}})
print("discounted:", res.modified_count)

res = products.update_one({"name": "Stapler"}, {"$set": {"price": 120}}, upsert=True)
print("upserted new id:", res.upserted_id is not None)

res = products.delete_many({"price": {"$lt": 70}})
print("deleted:", res.deleted_count)
print(sorted(p["name"] for p in products.find()))
Output
matched: 1 modified: 1
discounted: 2
upserted new id: True
deleted: 2
['Headphones', 'Mouse', 'Stapler']

Indexes and the aggregation pipeline

Python
from pymongo import MongoClient, ASCENDING
from pymongo.errors import DuplicateKeyError

db = MongoClient("mongodb://localhost:27017/")["shop"]
orders = db["orders"]
orders.drop()

orders.create_index([("order_no", ASCENDING)], unique=True)
orders.insert_many([
    {"order_no": 1, "city": "Pune", "total": 1200},
    {"order_no": 2, "city": "Mumbai", "total": 800},
    {"order_no": 3, "city": "Pune", "total": 450},
    {"order_no": 4, "city": "Mumbai", "total": 2300},
])
try:
    orders.insert_one({"order_no": 1, "city": "Delhi", "total": 99})
except DuplicateKeyError:
    print("order_no 1 already exists")

pipeline = [
    {"$match": {"total": {"$gte": 500}}},
    {"$group": {"_id": "$city", "orders": {"$sum": 1}, "revenue": {"$sum": "$total"}}},
    {"$sort": {"revenue": -1}},
]
for row in orders.aggregate(pipeline):
    print(row)
Output
order_no 1 already exists
{'_id': 'Mumbai', 'orders': 2, 'revenue': 3100}
{'_id': 'Pune', 'orders': 1, 'revenue': 1200}

Common Mistakes

  • Expecting schema enforcement by default — MongoDB accepts documents with typos in field names unless you add validation.
  • Forgetting $set in an update and accidentally trying to replace the whole document.
  • Querying large collections on fields without an index.
  • Printing ObjectId values and comparing them with strings — convert with str() or ObjectId().
  • Building queries from raw user input objects, which allows operator injection (e.g. {"$ne": null}).

Exercise

Using pymongo, insert two products into a products collection, print the names of the products that cost more than 100, and then raise the price of the pen to 15. This needs a running MongoDB server. When it works, the program prints {'name': 'bag'}.

Python · starter code
from pymongo import MongoClient

client = MongoClient("mongodb://localhost:27017")
products = client["shop"]["products"]

# TODO: insert {"name": "pen", "price": 12} and {"name": "bag", "price": 450}

# TODO: find the products with a price greater than 100, returning only the name,
#       and print each document

# TODO: set the price of the pen to 15
Show hints
  • A comparison is written as a nested dictionary: {"price": {"$gt": 100}}.
  • The second argument of find chooses the fields: {"_id": 0, "name": 1}. An update uses {"$set": {...}}.
Show solution
Python · solution
from pymongo import MongoClient

client = MongoClient("mongodb://localhost:27017")
products = client["shop"]["products"]

products.insert_many([
    {"name": "pen", "price": 12},
    {"name": "bag", "price": 450},
])

for document in products.find({"price": {"$gt": 100}}, {"_id": 0, "name": 1}):
    print(document)

products.update_one({"name": "pen"}, {"$set": {"price": 15}})

Quick quiz

1. What is the MongoDB equivalent of a table?

  • A. A document
  • B. A cluster
  • C. A field
  • D. A collection
Show answer

D. A collection holds documents, which correspond roughly to rows.

2. What does update_one(filter, {"$set": {"price": 15}}) change?

  • A. Only the price field of the first matching document
  • B. It replaces the whole document
  • C. Every document
  • D. Nothing unless upsert is set
Show answer

A. Without $set, the second argument would be rejected or would replace the document, depending on the method.

3. Which field does MongoDB add to every document that has none?

  • A. id
  • B. _id
  • C. key
  • D. uuid
Show answer

B. It is the primary key, an ObjectId by default.

Interview questions

What is the difference between SQL and NoSQL document databases?

Show answer

A relational database stores rows in tables with a fixed schema and relates tables through keys and joins, with strong transactional guarantees. A document database such as MongoDB stores self-contained documents whose structure can vary, often embedding related data inside the document, which avoids joins and makes it easy to scale across servers. Relational databases suit highly related, consistent data; document databases suit flexible or nested data that is read as a whole.

When should related data be embedded in a document and when referenced?

Show answer

Embed data that belongs to the parent, is read together with it and is limited in size, such as the address of an order. Reference data, by storing its id, when it is shared by many documents, changes independently or can grow without limit, such as the customer of an order or the comments on a popular post. The decision is driven by how the application reads the data.

Key Points to Remember

  • MongoDB stores documents (dicts) in collections; PyMongo is the official driver.
  • insert_one/insert_many, find/find_one, update_one/update_many, delete_one/delete_many.
  • Queries and updates are dicts with operators such as $gt, $in, $set, $inc and $push.
  • Indexes speed up queries and can enforce uniqueness.
  • The aggregation pipeline ($match, $group, $sort, $lookup) handles reporting and joins.

Practice in the playground

Write and run your own code for this topic, or start from the exercise or an example. Runs Python in your browser. Your code for each topic is kept in this browser.

Run the examples

Change an input, predict the result, then compare it with the output. Explain why the result changes.

These examples need a project environment on your computer, so they can be copied but not run here. Codelab runs Python, FastAPI backends with SQLite, plain Java 17 and HTML/CSS/JavaScript.

WebNest Studio

Written by

WebNest Studio Engineering Team

Practical lessons from developers working with Java, Python, React, databases and production systems.

Led by Vansh Duggal, Founder, WebNest Studio · Full-stack & software engineering