MongoDB’s querying capabilities make it a powerful choice for modern applications. With Python and the pymongo
library, you can easily interact with MongoDB to fetch, update, and manipulate data. At The Coding College, we’ll guide you through the essentials of performing queries in MongoDB using Python.
Prerequisites
Before diving into queries, 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
MongoDB Queries
A MongoDB query filters and retrieves specific documents from a collection based on conditions. Queries are written in JSON-like syntax and allow you to perform powerful data extraction.
Syntax
collection.find(query, projection)
query
: Filters documents based on specific criteria.projection
: Specifies which fields to include or exclude in the results.
Basic Query
The simplest query retrieves all documents in a collection.
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)
Query with Conditions
To filter documents, define a query object with key-value pairs representing the condition.
Example 1: Query by Equality
# Fetch documents where "city" is "New York"
query = {"city": "New York"}
for document in collection.find(query):
print(document)
Example 2: Query with Comparison Operators
MongoDB supports operators like $gt
, $lt
, $gte
, $lte
, $ne
, and $eq
.
# Fetch documents where "age" is greater than 25
query = {"age": {"$gt": 25}}
for document in collection.find(query):
print(document)
Query with Logical Operators
You can combine multiple conditions using $and
, $or
, $not
, and $nor
.
# 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)
Query with Fields
Specify the fields you want in the output using the projection
parameter.
# Include only "name" and "city" fields, exclude "_id"
query = {"city": "New York"}
projection = {"_id": 0, "name": 1, "city": 1}
for document in collection.find(query, projection):
print(document)
Complex Queries
Example 1: Query with Regular Expressions
Use regular expressions for pattern matching.
# Fetch documents where "name" starts with "A"
query = {"name": {"$regex": "^A"}}
for document in collection.find(query):
print(document)
Example 2: Query Nested Fields
To query nested fields, use dot notation.
# Fetch documents where "address.zip" is "12345"
query = {"address.zip": "12345"}
for document in collection.find(query):
print(document)
Useful Query Options
Sorting
Sort results by a specific field:
# Sort documents by "name" in ascending order
for document in collection.find().sort("name", 1):
print(document)
Limiting
Limit the number of results returned:
# Limit results to 5 documents
for document in collection.find().limit(5):
print(document)
Full Example
Here’s a script combining multiple query techniques:
import pymongo
# Connect to MongoDB
client = pymongo.MongoClient("mongodb://localhost:27017/")
db = client["company"]
collection = db["employees"]
# Query documents with multiple conditions
query = {"$and": [{"department": "IT"}, {"salary": {"$gte": 50000}}]}
projection = {"_id": 0, "name": 1, "salary": 1}
for document in collection.find(query, projection).sort("salary", -1).limit(3):
print(document)
Exercises
- Equality Query: Write a query to fetch documents where
age
equals 30. - Range Query: Fetch documents where
price
is between 100 and 500. - Regex Query: Find documents where
name
ends with “son”. - Combined Query: Fetch documents where
status
is “active” andbalance
is greater than 1000.
Common Errors
- Empty Query Result:
- If your query doesn’t match any document,
find()
returns an empty cursor. Double-check your conditions.
- If your query doesn’t match any document,
- Projection Confusion:
- Avoid mixing field inclusion and exclusion in the projection (except for
_id
).
- Avoid mixing field inclusion and exclusion in the projection (except for
- Syntax Issues:
- Ensure the query structure matches MongoDB’s JSON-like syntax.
Why Use Python MongoDB Queries?
MongoDB’s flexibility combined with Python’s simplicity enables developers to build efficient and scalable applications. Whether you’re working with large datasets or building real-time apps, understanding MongoDB queries is key.