Python MongoDB Tutorial – A Complete Beginner’s Guide
Last updated 5 months, 1 week ago | 371 views 75 5

MongoDB is one of the most popular NoSQL databases used in modern applications. Unlike traditional relational databases, MongoDB stores data in flexible, JSON-like documents. In this tutorial, we’ll walk you through how to use MongoDB with Python, from setup to CRUD operations.
Table of Contents
-
What is MongoDB?
-
Why Use MongoDB with Python?
-
Prerequisites
-
Installing PyMongo
-
Connecting to MongoDB
-
Creating a Database and Collection
-
CRUD Operations
-
Create (Insert)
-
Read (Find)
-
Update
-
Delete
-
-
Complete Working Example
-
Tips and Common Pitfalls
1. What is MongoDB?
MongoDB is a NoSQL, document-oriented database that stores data in BSON (Binary JSON). It's ideal for applications requiring scalability, flexibility, and real-time performance.
2. Why Use MongoDB with Python?
-
Python's dynamic typing and dictionaries align naturally with MongoDB's flexible schema
-
Great for data-driven applications, REST APIs, and rapid development
-
Supports horizontal scaling and real-time analytics
⚙️ 3. Prerequisites
-
Python installed (3.6+)
-
MongoDB Server installed and running (locally or remotely)
-
Basic knowledge of Python and JSON
4. Installing PyMongo
The official MongoDB driver for Python is PyMongo.
Install it using pip:
pip install pymongo
5. Connecting to MongoDB
import pymongo
client = pymongo.MongoClient("mongodb://localhost:27017/")
Connect to a Remote MongoDB Atlas Cluster:
client = pymongo.MongoClient("mongodb+srv://username:[email protected]/mydatabase")
6. Creating a Database and Collection
Create or Access a Database:
db = client["mydatabase"]
Create or Access a Collection (like a table in SQL):
collection = db["users"]
✅ MongoDB will create the database or collection only when you insert data.
✍️ 7. CRUD Operations in MongoDB
Create (Insert)
Insert one document:
user = {"name": "Alice", "age": 25}
collection.insert_one(user)
Insert multiple documents:
users = [
{"name": "Bob", "age": 30},
{"name": "Charlie", "age": 28}
]
collection.insert_many(users)
Read (Find)
Find one document:
user = collection.find_one()
print(user)
Find all documents:
for user in collection.find():
print(user)
With a filter:
for user in collection.find({"age": {"$gt": 25}}):
print(user)
✏️ Update
Update one document:
collection.update_one({"name": "Alice"}, {"$set": {"age": 26}})
Update many documents:
collection.update_many({}, {"$set": {"verified": True}})
❌ Delete
Delete one:
collection.delete_one({"name": "Bob"})
Delete many:
collection.delete_many({"verified": False})
8. Complete Working Example
import pymongo
# Connect to MongoDB
client = pymongo.MongoClient("mongodb://localhost:27017/")
db = client["company"]
employees = db["employees"]
# Insert documents
employees.insert_many([
{"name": "Alice", "role": "Engineer", "salary": 75000},
{"name": "Bob", "role": "Manager", "salary": 90000}
])
# Read documents
print("All Employees:")
for emp in employees.find():
print(emp)
# Update a document
employees.update_one({"name": "Alice"}, {"$set": {"salary": 80000}})
# Delete a document
employees.delete_one({"name": "Bob"})
9. Tips and Common Pitfalls
Tip / Pitfall | Advice |
---|---|
MongoDB is schema-less | You can store any structure, but plan your schema wisely |
_id field |
MongoDB auto-generates a unique _id , but you can assign your own |
JSON != BSON | MongoDB stores documents in BSON, which supports more data types |
Connection errors | Ensure MongoDB server is running and accessible |
Use indexes | For large datasets, create indexes on fields you query often |
Summary Table
Operation | Function |
---|---|
Insert One | insert_one() |
Insert Many | insert_many() |
Find One | find_one() |
Find Many | find() |
Update One | update_one() |
Update Many | update_many() |
Delete One | delete_one() |
Delete Many | delete_many() |
Final Thoughts
Python and MongoDB make a powerful pair for developers who need flexibility and performance. With PyMongo
, working with MongoDB is simple and intuitive, especially if you're used to Python dictionaries and JSON structures.
Whether you're building a small project or a large-scale system, MongoDB's document model and Python's flexibility can help you move fast and build efficiently.