🍃 Python Tutorial — MongoDB Database Connectivity

Introduction 🌟

MongoDB is a popular NoSQL document-based database that stores data in flexible JSON-like format. It is perfect for apps requiring scalability, schema flexibility, and fast reads/writes.

Python interacts with MongoDB using the pymongo library — the official MongoDB driver for Python.

Note

💡 MongoDB stores data as BSON (Binary JSON)
💡 Collections = tables, Documents = rows
💡 Schema-free → easy to modify structure

1. Installing PyMongo 📦

install_pymongo.sh

pip install pymongo

✔ Requires a running MongoDB server (local or cloud)

2. Connecting to MongoDB 🔌

connect_mongo.py

from pymongo import MongoClient

client = MongoClient("mongodb://localhost:27017/")
print("Connected!")

3. Selecting a Database 📚

select_db.py

db = client["mydatabase"]

4. Selecting a Collection 🗂️

select_collection.py

users = db["users"]

5. Inserting Documents ➕

Insert One Document

insert_one.py

user = {"name": "Sathish", "age": 25}
result = users.insert_one(user)

print(result.inserted_id)

Insert Many Documents

insert_many.py

users.insert_many([
    {"name": "Arun", "age": 22},
    {"name": "Priya", "age": 27}
])

6. Querying Documents 🔍

Find One

find_one.py

result = users.find_one({"name": "Sathish"})
print(result)

Find Many

find_many.py

for user in users.find({"age": {"$gt": 20}}):
    print(user)

Select Specific Fields

select_fields.py

for user in users.find({}, {"name": 1, "_id": 0}):
    print(user)

7. Updating Documents ✏️

update_one.py

users.update_one(
    {"name": "Sathish"},
    {"$set": {"age": 26}}
)

Update Multiple

update_many.py

users.update_many(
    {"age": {"$lt": 25}},
    {"$set": {"status": "young"}}
)

8. Deleting Documents ❌

delete_doc.py

users.delete_one({"name": "Arun"})
users.delete_many({"age": {"$gte": 30}})

9. Using Operators ($gt, $lt, $in, $regex, etc.) 🔧

operators.py

users.find({"age": {"$gt": 20}})
users.find({"name": {"$regex": "^S"}})
users.find({"age": {"$in": [22, 25, 27]}})

10. Sorting Results 📊

sort_docs.py

for user in users.find().sort("age", -1):
    print(user)

✔ -1 → descending, 1 → ascending

11. Limiting & Skipping Documents 📉

limit_skip.py

users.find().limit(5)
users.find().skip(10)

12. Counting Documents 🔢

count_docs.py

users.count_documents({"age": {"$gt": 20}})

13. Indexing for Faster Queries ⚡

create_index.py

users.create_index("name")
users.create_index([("age", 1)])

✔ Indexes drastically improve read performance

14. Working with Embedded Documents 🧩

embedded_docs.py

users.insert_one({
    "name": "Kumar",
    "address": {"city": "Chennai", "pin": 600001}
})

15. Aggregation Pipeline (Advanced Queries) 🔥

aggregation.py

pipeline = [
    {"$match": {"age": {"$gt": 20}}},
    {"$group": {"_id": "$age", "count": {"$sum": 1}}}
]

for doc in users.aggregate(pipeline):
    print(doc)

✔ Aggregation is MongoDB’s powerful query engine

16. MongoDB Atlas (Cloud Connection) ☁️

atlas_connect.py

client = MongoClient(
    "mongodb+srv://username:password@cluster0.mongodb.net/mydatabase"
)

Note

✔ Perfect for cloud-backed apps

17. Deleting a Collection or Database ⚠️

drop_operations.py

users.drop()          # drop collection
client.drop_database("mydatabase")

18. Closing the Connection 🔚

close.py

client.close()

19. Full CRUD Example 📝

mongo_crud.py

from pymongo import MongoClient

client = MongoClient("mongodb://localhost:27017/")
db = client["crud_demo"]
tasks = db["tasks"]

def add_task(title):
    tasks.insert_one({"title": title})

def get_tasks():
    return list(tasks.find())

def delete_task(title):
    tasks.delete_one({"title": title})

# Usage
add_task("Learn MongoDB")
print(get_tasks())

MongoDB Cheat Sheet 📘

OperationCommand
Insertinsert_one(), insert_many()
Selectfind(), find_one()
Updateupdate_one(), update_many()
Deletedelete_one(), delete_many()
Sortsort()
Countcount_documents()
Aggregateaggregate()

Best Practices 💡

  • ✔ Always index frequently searched fields
  • ✔ Use schema validation for large projects
  • ✔ Avoid large documents (16MB max)
  • ✔ Use MongoDB Atlas for production systems
  • ✔ Use aggregation pipelines for analytics

Conclusion 🎉

>>“MongoDB + Python provides flexible, scalable, and lightning-fast data handling for modern applications.” ✨

You now fully understand MongoDB Database Connectivity in Python! Want the next topic? Try SQLAlchemy ORM, FastAPI + MongoDB, Async MongoDB with Motor, or Redis Connectivity. Just tell me! 😊