MongoDB Query
Filter and search documents with advanced query conditions
🔍 Advanced Querying
MongoDB queries allow you to filter documents using various conditions. You can search for specific values, ranges, patterns, and complex combinations to find exactly what you need.
import pymongo
client = pymongo.MongoClient("mongodb://localhost:27017/")
db = client["store"]
products = db["products"]
# Find products over $50
expensive = products.find({"price": {"$gt": 50}})
for product in expensive:
print(product["name"], product["price"])
Query Operators
Comparison
Compare values with operators
# Price greater than 100
products.find({"price": {"$gt": 100}})
Text Search
Search text with patterns
# Names starting with "A"
users.find({"name": {"$regex": "^A"}})
Array Matching
Find values in arrays
# Category in list
products.find({"category": {"$in": ["books", "toys"]}})
Logical Operators
Combine multiple conditions
# Price between 10 and 50
products.find({"$and": [{"price": {"$gt": 10}}, {"price": {"$lt": 50}}]})
Comparison Operators
Filter documents by comparing field values
import pymongo
client = pymongo.MongoClient("mongodb://localhost:27017/")
db = client["shop"]
products = db["products"]
# Greater than ($gt)
expensive = products.find({"price": {"$gt": 100}})
print("Expensive products:")
for item in expensive:
print(f"- {item['name']}: ${item['price']}")
# Less than or equal ($lte)
affordable = products.find({"price": {"$lte": 50}})
print("\nAffordable products:")
for item in affordable:
print(f"- {item['name']}: ${item['price']}")
# Not equal ($ne)
not_books = products.find({"category": {"$ne": "books"}})
print("\nNon-book items:")
for item in not_books:
print(f"- {item['name']} ({item['category']})")
Array and List Queries
Search for values within arrays or match against lists
# Find products in specific categories
categories = ["electronics", "books", "toys"]
filtered = products.find({"category": {"$in": categories}})
print("Products in selected categories:")
for item in filtered:
print(f"- {item['name']} ({item['category']})")
# Find products NOT in categories
excluded = products.find({"category": {"$nin": ["clothing", "food"]}})
print("\nProducts excluding clothing and food:")
for item in excluded:
print(f"- {item['name']} ({item['category']})")
Text Pattern Matching
Search text fields using regular expressions
# Find names starting with "A"
starts_with_a = products.find({"name": {"$regex": "^A"}})
print("Products starting with 'A':")
for item in starts_with_a:
print(f"- {item['name']}")
# Find names containing "phone" (case insensitive)
phones = products.find({"name": {"$regex": "phone", "$options": "i"}})
print("\nPhone products:")
for item in phones:
print(f"- {item['name']}")
# Find names ending with "book"
books = products.find({"name": {"$regex": "book$", "$options": "i"}})
print("\nBook products:")
for item in books:
print(f"- {item['name']}")
Logical Operators
Combine multiple conditions with AND, OR, NOT
# AND: Both conditions must be true
mid_range = products.find({
"$and": [
{"price": {"$gt": 20}},
{"price": {"$lt": 100}}
]
})
print("Mid-range products ($20-$100):")
for item in mid_range:
print(f"- {item['name']}: ${item['price']}")
# OR: Either condition can be true
cheap_or_books = products.find({
"$or": [
{"price": {"$lt": 15}},
{"category": "books"}
]
})
print("\nCheap items or books:")
for item in cheap_or_books:
print(f"- {item['name']}: ${item['price']} ({item['category']})")
# NOT: Reverse a condition
not_expensive = products.find({
"$not": {"price": {"$gt": 100}}
})
print("\nNot expensive items:")
for item in not_expensive:
print(f"- {item['name']}: ${item['price']}")
Practical Query Examples
Real-world query scenarios
# E-commerce: Find products on sale
def find_sale_items():
sale_products = products.find({
"$and": [
{"on_sale": True},
{"stock": {"$gt": 0}}
]
})
print("Items on sale (in stock):")
for item in sale_products:
print(f"- {item['name']}: ${item['price']} (Stock: {item['stock']})")
# User management: Find active users from specific cities
def find_local_users():
users = db["users"]
local_active = users.find({
"$and": [
{"city": {"$in": ["New York", "Los Angeles", "Chicago"]}},
{"active": True},
{"last_login": {"$exists": True}}
]
})
print("Active users in major cities:")
for user in local_active:
print(f"- {user['name']} from {user['city']}")
# Run examples
find_sale_items()
find_local_users()