MongoDB Find Documents
Learn how to retrieve and search documents from MongoDB collections
🔍 Finding Your Data
Finding documents is how you retrieve data from MongoDB. You can find all documents, find specific ones using filters, or find just the first match. MongoDB uses flexible query syntax to help you find exactly what you need.
import pymongo
# Connect to MongoDB
client = pymongo.MongoClient("mongodb://localhost:27017/")
db = client["mystore"]
collection = db["products"]
# Find all documents
all_products = collection.find()
for product in all_products:
print(product)
# Find specific document
laptop = collection.find_one({"name": "Laptop"})
print(laptop)
Find Methods
Find All
Get all documents in collection
all_docs = collection.find()
for doc in all_docs:
print(doc)
Find One
Get first matching document
user = collection.find_one({"name": "John"})
print(user)
Find with Filter
Search with specific conditions
adults = collection.find({"age": {"$gte": 18}})
for adult in adults:
print(adult["name"])
Count Results
Count matching documents
count = collection.count_documents({"age": {"$gte": 18}})
print(f"Adults: {count}")
Find All Documents
Use find() to retrieve all documents from a collection
import pymongo
# Connect to database
client = pymongo.MongoClient("mongodb://localhost:27017/")
db = client["school"]
students = db["students"]
# Find all students
all_students = students.find()
print("All students:")
for student in all_students:
print(f"Name: {student['name']}, Age: {student['age']}")
# Alternative: Convert to list
student_list = list(students.find())
print(f"Total students: {len(student_list)}")
Find One Document
Use find_one() to get the first matching document
# Find first student
first_student = students.find_one()
print("First student:", first_student)
# Find specific student by name
john = students.find_one({"name": "John Doe"})
if john:
print(f"Found: {john['name']}, Grade: {john['grade']}")
else:
print("Student not found")
# Find by ID
from bson import ObjectId
student_id = ObjectId("507f1f77bcf86cd799439011") # Example ID
student = students.find_one({"_id": student_id})
Find with Filters
Use query filters to find specific documents
🔹 Simple Filters
# Find students with grade A
a_students = students.find({"grade": "A"})
print("A-grade students:")
for student in a_students:
print(f" - {student['name']}")
# Find students aged 20
twenty_year_olds = students.find({"age": 20})
for student in twenty_year_olds:
print(f"Age 20: {student['name']}")
🔹 Comparison Operators
# Find students older than 19
older_students = students.find({"age": {"$gt": 19}})
# Find students 18 or older
adults = students.find({"age": {"$gte": 18}})
# Find students younger than 21
young_students = students.find({"age": {"$lt": 21}})
# Find students not aged 20
not_twenty = students.find({"age": {"$ne": 20}})
Select Specific Fields
Choose which fields to include or exclude from results
# Include only name and grade (exclude _id)
students_basic = students.find({}, {"name": 1, "grade": 1, "_id": 0})
for student in students_basic:
print(student) # Only shows name and grade
# Exclude age field (include everything else)
students_no_age = students.find({}, {"age": 0})
for student in students_no_age:
print(student) # Shows all fields except age
Practical Examples
Real-world scenarios for finding documents
🔹 E-commerce Search
products = db["products"]
# Find products in Electronics category
electronics = products.find({"category": "Electronics"})
# Find products under $100
affordable = products.find({"price": {"$lt": 100}})
# Find in-stock products
available = products.find({"in_stock": True})
# Count products by category
electronics_count = products.count_documents({"category": "Electronics"})
print(f"Electronics products: {electronics_count}")
🔹 User Management
users = db["users"]
# Find active users
active_users = users.find({"status": "active"})
# Find users by email domain
gmail_users = users.find({"email": {"$regex": "@gmail.com$"}})
# Check if user exists
user_exists = users.find_one({"username": "john_doe"})
if user_exists:
print("User found!")
else:
print("User not found")