Want to use a MongoDB database in Python without any framework? This hands-on PyMongo tutorial will help you connect Python to MongoDB, model real data, and run Python MongoDB CRUD with clean, reusable code. Consider treating this like a practical Python MongoDB example that you can copy, tweak, and ship today.
Why Use MongoDB with Python?
MongoDB pairs naturally with Python because:
- Documents map to Python dicts, so data feels native.
- You can move fast: prototype today, scale tomorrow.
- Rich queries, indexes, and aggregations cover real use cases.
- Local dev is easy; MongoDB Atlas handles cloud scale.
- PyMongo stays lightweight and great for scripts, CLIs, and microservices.
New to setup? Read my MongoDB installation guide and come back: MongoDB installation guide
Install the PyMongo package
In further example, you will use PyMongo python library for performing MongoBD database operation in Python. Before moving forward you need to install it into your local machine. Open terminal and enter below command to install PyMongo package:
pip install pymongoNext thing you need is connection string. If you are working on local development then mongodb://localhost:27017 will work. However for Atlas development, you need to provide connection string into below format:
mongodb+srv://<user>:<password>@<cluster-url>/<db>?retryWrites=true&w=majorityPython MongoDB Examples
Let’s try to setup MongoDB operation in python like CRUD operation for data or query MongoDB data and many more things. You’ll Connect Python to MongoDB once, then run clean CRUD operations that fit everyday tasks like loyalty tracking or mailing lists.
Reusable Connecting MongoDB Database In Python
Let’s create a reusable function so your scripts share one connection. It will help you to reuse same connection object for performing multiple operations like insert, update or delete.
from pymongo import MongoClient
def get_db(uri, db_name):
client = MongoClient(uri, serverSelectionTimeoutMS=5000)
client.admin.command("ping")
return client[db_name]
db = get_db("mongodb://localhost:27017", "shopdb")As you can see, here we have created function to connect with MongoDB database in python. It will content to database and return object.
Creating MongoDB Collection In Python
Get a handle to the collection and add helpful indexes. MongoDB will automatically generates collection or tables whenever you try to insert or update data.
customers = db["customers"]
customers.create_index("email", unique=True)
customers.create_index([("city", 1), ("name", 1)])Insert Operation in MongoDB Python
Let’s try to insert single or multiple data into MongoDB collection in Python. Let’s assume we have customers collection where you insert customers data into that.
one = customers.insert_one({"name": "Ava Patel", "email": "ava@example.com", "city": "Austin", "loyalty": 0})
many = customers.insert_many([
{"name": "Liam Chen", "email": "liam@example.com", "city": "Austin", "loyalty": 5},
{"name": "Mia Lopez", "email": "mia@example.com", "city": "Denver", "loyalty": 2},
{"name": "Noah King", "email": "noah@example.com", "city": "Dallas", "loyalty": 1}
])
print(one.inserted_id)
print(many.inserted_ids)Here, you will insert single or multiple records into collection and print inserted IDs to the users.
Query Operation in MongoDB Python
Fetch a single profile, a filtered list, and a paginated slice.
profile = customers.find_one({"email": "ava@example.com"}, {"_id": 0, "name": 1, "city": 1, "loyalty": 1})
print(profile)
austin_names = list(customers.find({"city": "Austin"}, {"_id": 0, "name": 1}).sort("name", 1))
print(austin_names)
page_size = 2
page = 1
paged = list(customers.find({}, {"_id": 0, "name": 1, "city": 1}).sort("name", 1).skip(page_size * (page - 1)).limit(page_size))
print(paged)
count_tx = customers.count_documents({"city": {"$in": ["Austin", "Dallas"]}})
print(count_tx)In above example, we have performed different types of query operation for MongoDB Database via Python script.
Update Operation in MongoDB Python
Adjust loyalty points and keep profiles current. Upsert creates a new doc on demand.
u1 = customers.update_one({"email": "ava@example.com"}, {"$set": {"city": "Dallas"}, "$inc": {"loyalty": 3}})
print(u1.matched_count, u1.modified_count)
u2 = customers.update_many({"city": "Austin"}, {"$inc": {"loyalty": 1}})
print(u2.modified_count)
u3 = customers.update_one(
{"email": "sam@example.com"},
{"$setOnInsert": {"name": "Sam Rivera", "email": "sam@example.com", "city": "Seattle", "loyalty": 0}},
upsert=True
)
print(u3.upserted_id)Delete Operation in MongoDB Python
Removing or deleting data from database is daily task for any developer.
d1 = customers.delete_one({"email": "mia@example.com"})
print(d1.deleted_count)
d2 = customers.delete_many({"loyalty": {"$lt": 1}})
print(d2.deleted_count)These Python MongoDB CRUD patterns mirror real life example fo customers, filter by city for email campaigns, bump loyalty after purchases, and clean up noise.
Conclusion
You just saw how to use MongoDB Database in Python with a reusable connection, clean collection handles, and practical CRUD. This Connect Python to MongoDB flow goes from scripts to services, and each of the above Python MongoDB examples fits real life.

