Retrieving data is one of the core operations when working with databases. MongoDB, with its flexible query system, allows developers to fetch data effortlessly. Using Python’s pymongo
library, you can perform powerful queries to extract the information you need. At The Coding College, we help simplify such operations for you!
Prerequisites
Before diving into the examples, ensure you have the following:
- Python Installed: Download it from python.org.
- MongoDB Installed: Install it from mongodb.com.
pymongo
Installed: Install the driver using:
pip install pymongo
The find()
Method
In MongoDB, the find()
method retrieves documents from a collection. By default, it fetches all documents unless specific conditions (queries) are applied.
Syntax
collection.find(query, projection)
query
: Filters documents based on specified conditions (default is{}
to fetch all documents).projection
: Specifies which fields to include or exclude in the result.
Example 1: Fetch All Documents
Use find()
without arguments to retrieve all documents:
import pymongo
# Connect to MongoDB
client = pymongo.MongoClient("mongodb://localhost:27017/")
db = client["mydatabase"]
collection = db["customers"]
# Fetch all documents
for document in collection.find():
print(document)
Example 2: Fetch Documents with a Query
To filter documents, pass a query object:
# Fetch documents where "city" is "New York"
query = {"city": "New York"}
for document in collection.find(query):
print(document)
Example 3: Include/Exclude Fields
Use the projection
parameter to limit the fields in the result:
# Fetch documents with "name" and exclude "_id"
query = {"city": "New York"}
projection = {"_id": 0, "name": 1, "city": 1}
for document in collection.find(query, projection):
print(document)
Example 4: Fetch with Comparison Operators
MongoDB supports operators like $gt
, $lt
, $eq
, etc.:
# Fetch documents where "age" is greater than 25
query = {"age": {"$gt": 25}}
for document in collection.find(query):
print(document)
Example 5: Fetch Documents with Logical Operators
Combine conditions using $and
, $or
, $not
, and more:
# Fetch documents where "age" is greater than 25 OR "city" is "Chicago"
query = {"$or": [{"age": {"$gt": 25}}, {"city": "Chicago"}]}
for document in collection.find(query):
print(document)
Example 6: Sort the Results
Sort documents using sort()
method:
# Sort by "name" in ascending order
for document in collection.find().sort("name", 1):
print(document)
Example 7: Limit the Number of Results
Use limit()
to restrict the number of documents returned:
# Fetch only 3 documents
for document in collection.find().limit(3):
print(document)
Complete Example
Here’s a complete script combining multiple features:
import pymongo
# Connect to MongoDB
client = pymongo.MongoClient("mongodb://localhost:27017/")
db = client["company"]
collection = db["employees"]
# Fetch documents based on query, projection, and sort
query = {"salary": {"$gte": 50000}}
projection = {"_id": 0, "name": 1, "salary": 1}
for document in collection.find(query, projection).sort("salary", -1).limit(5):
print(document)
Exercises
- Basic Query: Write a script to fetch all documents from a
products
collection. - Field Projection: Fetch documents from a
users
collection, displaying onlyname
andemail
. - Filter and Sort: Query documents where
age
is less than 30, sorted byname
in descending order.
Common Errors
- Empty Result:
- If your query doesn’t match any document,
find()
returns an empty cursor. Double-check your query.
- If your query doesn’t match any document,
- Projection Errors:
- Mixing inclusion and exclusion in
projection
(except_id
) will raise an error.
- Mixing inclusion and exclusion in
Why Use MongoDB’s find()
?
The find()
method is powerful and flexible, allowing developers to extract data efficiently. Combined with Python, it provides a robust tool for handling and analyzing data.