Step by Step Guide to Connecting Python with MongoDB Using PyMongo for CRUD Operation
- Sharon Rajendra Manmothe

- Aug 29
- 1 min read
Step 1: Install Required Tools
Install Python
Download from python.org
Verify:
python --version
Install MongoDB (Local)
Download from mongodb.com/try/download/community
Start MongoDB server:
mongod
OR use MongoDB Atlas (Cloud) (free cluster).
Install VS Code
Download VS Code
Install the Python extension (by Microsoft).
Install PyMongo Driver Open VS Code Terminal and run:
pip install pymongo dnspython
Create Project in VS Code
Create a new folder → mongodb_python_app.

Open it in VS Code (File > Open Folder).
Create a new file → app.py.
Step 3: Write Python Code
Paste this into app.py:
from pymongo import MongoClient# 1. Connect to local MongoDB (make sure mongod is running)client = MongoClient("mongodb://localhost:27017/")# 2. Create or switch to databasedb = client["school_db"]# 3. Create or switch to collectionstudents = db["students"]# 4. Insert a documentstudent1 = {"name": "Rohan", "age": 23, "course": "Computer Science"}students.insert_one(student1)# 5. Insert multiple documentsstudent_list = [ {"name": "Raj", "age": 21, "course": "Mathematics"}, {"name": "Priya", "age": 22, "course": "Physics"}]students.insert_many(student_list)# 6. Fetch all documentsprint("\nAll Students:")for doc in students.find(): print(doc)# 7. Fetch with conditionprint("\nStudents enrolled in Physics:")for doc in students.find({"course": "Physics"}): print(doc)# 8. Update a documentstudents.update_one({"name": "Sharon"}, {"$set": {"course": "Data Science"}})print("\nAfter Update:")for doc in students.find({"name": "Sharon"}): print(doc)# 9. Delete a documentstudents.delete_one({"name": "Raj"})print("\nAfter Deletion:")for doc in students.find(): print(doc)
Step 4: Run in VS Code
Open terminal in VS Code (Ctrl + ~).
Run:
python app.py
Step 5: Verify in MongoDB Compass
Open MongoDB Compass.
Connect to the same URI you used in Python.
Browse school → students collection.

$50
Product Title
Product Details goes here with the simple product description and more information can be seen by clicking the see more button. Product Details goes here with the simple product description and more information can be seen by clicking the see more button

$50
Product Title
Product Details goes here with the simple product description and more information can be seen by clicking the see more button. Product Details goes here with the simple product description and more information can be seen by clicking the see more button.

$50
Product Title
Product Details goes here with the simple product description and more information can be seen by clicking the see more button. Product Details goes here with the simple product description and more information can be seen by clicking the see more button.



Comments