MongoDB is a popular NoSQL document database. Instead of tables and rows it stores flexible JSON-like documents in collections, so each record can have its own fields. It is widely used for web apps, product catalogues, logs and IoT data.
What You Will Learn
- SQL vs NoSQL and when to use each
- Documents, collections and databases
- Insert, find, update and delete with pymongo
- Query operators and projections
- Aggregation pipelines and indexes
Prerequisites
SQL Basics (for comparison) and Python dictionaries.
SQL vs MongoDB
| SQL (relational) | MongoDB |
|---|---|
| Database | Database |
| Table | Collection |
| Row | Document |
| Column | Field |
| Fixed schema | Flexible schema |
| JOIN | Embedded documents or $lookup |
Install
docker run -d -p 27017:27017 --name mongo mongo:7
pip install pymongo
Or use a free cloud cluster on MongoDB Atlas.
Insert Documents
from pymongo import MongoClient
client = MongoClient("mongodb://localhost:27017")
db = client["institute"]
students = db["students"]
students.insert_many([
{"name": "Aman", "city": "Ludhiana", "age": 21, "skills": ["python", "sql"]},
{"name": "Riya", "city": "Jalandhar", "age": 23, "skills": ["python", "ml"],
"address": {"pin": "144001"}},
{"name": "Karan", "city": "Ludhiana", "age": 25, "skills": ["dl"]},
])
print(students.count_documents({}))
3
Explanation: Documents are Python dictionaries. Riya has an address field the others do not – that is allowed. MongoDB adds a unique _id to every document.
Find (Read)
for s in students.find({"city": "Ludhiana", "age": {"$gt": 21}}, {"_id": 0, "name": 1, "age": 1}):
print(s)
print(students.find_one({"skills": "ml"})["name"])
{'name': 'Karan', 'age': 25}
Riya
Explanation: The first argument is the filter, the second the projection (which fields to return). Searching an array field for a value matches any element.
| Operator | Meaning |
|---|---|
| $gt, $gte, $lt, $lte | Greater / less than |
| $ne | Not equal |
| $in | Value in a list |
| $and, $or | Combine conditions |
| $exists | Field is present |
| $regex | Pattern match |
Update and Delete
students.update_one({"name": "Aman"}, {"$set": {"age": 22}, "$push": {"skills": "pandas"}})
students.delete_many({"age": {"$lt": 18}})
Aggregation Pipeline
pipeline = [
{"$group": {"_id": "$city", "students": {"$sum": 1}, "avg_age": {"$avg": "$age"}}},
{"$sort": {"students": -1}}
]
for row in students.aggregate(pipeline):
print(row)
{'_id': 'Ludhiana', 'students': 2, 'avg_age': 23.5}
{'_id': 'Jalandhar', 'students': 1, 'avg_age': 23.0}
Explanation: Each stage transforms the documents: $group is like GROUP BY, $sort like ORDER BY. Other stages include $match (WHERE), $project and $lookup (JOIN). Ludhiana’s average is 23.5 because Aman’s age was updated to 22 above.
Indexes
students.create_index("city")
students.create_index([("name", 1)], unique=True)
When to Choose MongoDB
| Choose MongoDB for | Choose SQL for |
|---|---|
| Changing or varied fields | Strict structure and relationships |
| Nested data (orders with items) | Many joins and complex transactions |
| Fast development, JSON APIs | Financial and reporting systems |
Common Errors
| Problem | Cause and fix |
|---|---|
ServerSelectionTimeoutError |
MongoDB is not running or the connection string is wrong. |
| Query finds nothing | Field names and values are case-sensitive. |
DuplicateKeyError |
A unique index already has that value. |
Series
SQL series: SQL Basics · MySQL · PostgreSQL · MongoDB · Database Design · SQL for Data Analytics · Advanced SQL Queries · Python MySQL series
Interview Questions
Q: What is a document in MongoDB?
A JSON-like (BSON) record made of field–value pairs, which can contain arrays and nested documents.
Q: Embed or reference?
Embed data read together (order items in an order); reference data shared by many documents (customer in orders).
Practice Exercises
- Find all students who know “python” and live in Ludhiana.
- Write an aggregation that counts how many students have each skill (use
$unwind).
Summary
MongoDB stores flexible documents in collections. With pymongo you insert, find, update and delete using dictionaries, and use aggregation pipelines and indexes for analysis and speed.
Next: Database Design · SQL Basics
Machine Learning Tutorials, Courses and Certifications