Python MongoDB Tutorial – How to Find Documents with PyMongo
Last updated 5 months, 1 week ago | 474 views 75 5

Retrieving data is one of the most common tasks when working with databases. In MongoDB, you can find documents using simple queries or advanced filters. This tutorial will teach you how to use Python and PyMongo to find documents in MongoDB, whether you're searching for a single record or multiple results.
Table of Contents
-
What is the Find Operation in MongoDB?
-
Prerequisites
-
Installing PyMongo
-
Connecting to MongoDB
-
Inserting Sample Data
-
Using
find_one()
to Retrieve One Document -
Using
find()
to Retrieve Multiple Documents -
Filtering Queries
-
Using Projection to Limit Fields
-
Full Working Example
-
Tips and Common Pitfalls
1. What is the Find Operation in MongoDB?
The find()
operation in MongoDB is used to retrieve documents from a collection. You can fetch:
-
A single document with
find_one()
-
Multiple documents with
find()
MongoDB uses JSON-like query syntax to filter results.
⚙️ 2. Prerequisites
-
Python installed (3.x)
-
MongoDB running (locally or via MongoDB Atlas)
-
pymongo
installed
3. Installing PyMongo
Install the MongoDB driver for Python using pip:
pip install pymongo
4. Connecting to MongoDB
Connect to Local Server:
import pymongo
client = pymongo.MongoClient("mongodb://localhost:27017/")
Connect to MongoDB Atlas (Cloud):
client = pymongo.MongoClient("mongodb+srv://username:[email protected]/?retryWrites=true&w=majority")
Replace placeholders with your actual Atlas credentials.
5. Inserting Sample Data
We'll use a collection named users
for examples:
db = client["mydatabase"]
collection = db["users"]
collection.insert_many([
{"name": "Alice", "age": 25, "email": "[email protected]"},
{"name": "Bob", "age": 30, "email": "[email protected]"},
{"name": "Charlie", "age": 28, "email": "[email protected]"}
])
6. Using find_one()
to Retrieve One Document
user = collection.find_one()
print(user)
You can also filter:
user = collection.find_one({"name": "Alice"})
print(user)
Output:
{'_id': ObjectId('...'), 'name': 'Alice', 'age': 25, 'email': '[email protected]'}
7. Using find()
to Retrieve Multiple Documents
for user in collection.find():
print(user)
This returns a cursor that you can iterate over.
8. Filtering Queries with Conditions
Use query filters to match specific documents.
Find by field value:
query = {"age": 30}
for user in collection.find(query):
print(user)
Find documents where age is greater than 25:
query = {"age": {"$gt": 25}}
for user in collection.find(query):
print(user)
Other MongoDB operators:
Operator | Description |
---|---|
$gt |
Greater than |
$lt |
Less than |
$gte |
Greater than or equal |
$lte |
Less than or equal |
$ne |
Not equal |
$in |
In a list |
9. Using Projection to Limit Fields
You can control which fields to return using projection:
for user in collection.find({}, {"_id": 0, "name": 1, "email": 1}):
print(user)
This will return only name
and email
, excluding _id
.
10. Full Working Example
import pymongo
# Connect to MongoDB
client = pymongo.MongoClient("mongodb://localhost:27017/")
db = client["mydatabase"]
collection = db["users"]
# Insert data (optional, if collection is empty)
if collection.count_documents({}) == 0:
collection.insert_many([
{"name": "Alice", "age": 25, "email": "[email protected]"},
{"name": "Bob", "age": 30, "email": "[email protected]"},
{"name": "Charlie", "age": 28, "email": "[email protected]"}
])
# Find one document
print("Find one:")
print(collection.find_one())
# Find all documents
print("\nFind all:")
for user in collection.find():
print(user)
# Filter by condition
print("\nUsers aged over 25:")
for user in collection.find({"age": {"$gt": 25}}):
print(user)
# Projection
print("\nName and email only:")
for user in collection.find({}, {"_id": 0, "name": 1, "email": 1}):
print(user)
11. Tips and Common Pitfalls
Tip / Pitfall | Solution |
---|---|
Don't forget to loop through find() results |
It's a cursor, not a list |
Use projection to optimize performance | Especially when documents have many fields |
MongoDB allows dynamic schemas | Be careful with inconsistent field names |
Querying non-existent fields returns nothing | Check your field spelling and case |
Always check if data exists before querying | Avoid empty results or errors |
✅ Conclusion
The find()
and find_one()
methods in PyMongo are essential tools for querying data in MongoDB. Whether you're retrieving a single document or filtering complex results with conditions and projections, these tools give you powerful access to your data.
MongoDB's flexibility and Python's simplicity make them a great combination for modern data-driven applications.