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
| SQL | MongoDB |
|---|---|
| Table | Collection |
| Row | Document |
| Column | Field |
| SELECT ... WHERE | find({...}) |
| INSERT | insert_one |
| UPDATE | update_one |
| DELETE | delete_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
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