the full guide

Python with MongoDB

MongoDB is a NoSQL document database. It stores flexible JSON-like documents in collections, with no fixed table structure. Python uses it through the pymongo library.

10 min Intermediate

What you need: The earlier topics of this module.

Definition

MongoDB is a NoSQL document database. It stores flexible JSON-like documents in collections, with no fixed table structure. Python uses it through the pymongo library.

In simple words

SQL is a form where every row has the same boxes. MongoDB is a folder of notes, where each note can have different fields. It's flexible, and that flexibility also lets mess in.

Why it matters

It suits data whose shape changes or nests deeply, such as user profiles or logs. Many LLM apps store chats and documents this way.

How it works

SQLMongoDB
TableCollection
RowDocument
ColumnField
SELECT ... WHEREfind({...})
INSERTinsert_one
UPDATEupdate_one
DELETEdelete_one
pip install pymongo

import os
from pymongo import MongoClient

client = MongoClient(os.environ["MONGO_URL"])
students = client["school"]["students"]

students.insert_one({"name": "Riya", "marks": {"maths": 91}, "city": "Pune"})

for s in students.find({"marks.maths": {"$gt": 80}}).sort("name").limit(5):
    print(s["name"])

students.update_one({"name": "Riya"}, {"$set": {"city": "Delhi"}})
students.delete_one({"name": "Riya"})

Common mistakes

  • Choosing MongoDB to avoid thinking about structure. You still need a design.
  • Forgetting indexes, so queries slow down as data grows.

Check yourself

Question 1

1. In MongoDB, what's the equivalent of a row?

Question 2

2. What does {"$gt": 80} mean?

Summary

  • MongoDB stores flexible JSON-like documents.
  • Collection, document and field map to table, row and column.
  • Choose it when the shape truly varies.

Finished reading?

Sources: PyMongo documentation