Python MongoDB

🐍 Python MongoDB — Complete Guide

MongoDB is a NoSQL database that stores data in JSON-like documents.
Python can interact with MongoDB using the pymongo library.


 1️⃣ Install PyMongo

pip install pymongo

 2️⃣ Connect to MongoDB

from pymongo import MongoClient

# Connect to local MongoDB server
client = MongoClient(“mongodb://localhost:27017/”)

# Create or access database
db = client[“testdb”]

print(“✅ Connected to MongoDB”)

Replace localhost:27017 if you have a remote MongoDB server.


 3️⃣ Create a Collection

# Create or access collection
students_col = db["students"]

Collections are like tables in SQL.


 4️⃣ Insert Documents

# Single document
student1 = {"name": "Vipul", "age": 25, "courses": ["Python", "Java"]}
students_col.insert_one(student1)
# Multiple documents
students = [
{“name”: “Riya”, “age”: 22, “courses”: [“C++”]},
{“name”: “Amit”, “age”: 24, “courses”: [“JavaScript”, “Python”]}
]
students_col.insert_many(students)print(“✅ Documents inserted”)

 5️⃣ Read Documents

# Find all documents
all_students = students_col.find()
for student in all_students:
print(student)
# Find one document
student = students_col.find_one({“name”: “Vipul”})
print(student)# Find with condition
students_under_25 = students_col.find({“age”: {“$lt”: 25}})
for s in students_under_25:
print(s)

 6️⃣ Update Documents

# Update one
students_col.update_one(
{"name": "Vipul"},
{"$set": {"age": 26}}
)
# Update many
students_col.update_many(
{“age”: {“$lt”: 25}},
{“$set”: {“status”: “young”}}
)

 7️⃣ Delete Documents

# Delete one
students_col.delete_one({"name": "Riya"})
# Delete many
students_col.delete_many({“age”: {“$gt”: 30}})

 8️⃣ Query Operators

Operator Description Example
$lt Less than {"age": {"$lt": 25}}
$gt Greater than {"age": {"$gt": 20}}
$lte Less than or equal {"age": {"$lte": 25}}
$gte Greater than or equal {"age": {"$gte": 20}}
$ne Not equal {"name": {"$ne": "Vipul"}}
$in In list {"age": {"$in": [22,24]}}
$nin Not in list {"age": {"$nin": [22,24]}}

 9️⃣ Sorting and Limiting

# Sort by age ascending
for s in students_col.find().sort("age", 1):
print(s)
# Sort by age descending and limit 2
for s in students_col.find().sort(“age”, –1).limit(2):
print(s)

 10️⃣ Drop Collection or Database

# Drop collection
students_col.drop()
# Drop database
client.drop_database(“testdb”)

 11️⃣ Full Example: CRUD in MongoDB


 


MongoDB Advantages in Python:

  • Schema-less, flexible data

  • Stores complex JSON-like documents

  • Fast for reads/writes

  • Easy integration with Python via pymongo

CodeCapsule

Sanjit Sinha — Web Developer | PHP • Laravel • CodeIgniter • MySQL • Bootstrap Founder, CodeCapsule — Student projects & practical coding guides. Email: info@codecapsule.in • Website: CodeCapsule.in

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *