169 lines
4.8 KiB
Python
169 lines
4.8 KiB
Python
"""
|
|
MongoDB Operations Examples
|
|
|
|
This module provides practical examples of using MongoDB operations through our mixins.
|
|
Each example demonstrates different aspects of CRUD operations and aggregation.
|
|
"""
|
|
|
|
from typing import Dict, List, Any
|
|
from datetime import datetime
|
|
|
|
from Services.MongoDb.database import mongodb
|
|
|
|
|
|
def insert_examples() -> None:
|
|
"""Examples of insert operations."""
|
|
# Single document insert
|
|
user_doc = {
|
|
"username": "john_doe",
|
|
"email": "john@example.com",
|
|
"age": 30,
|
|
"created_at": datetime.utcnow(),
|
|
}
|
|
user_id = mongodb.insert_one(
|
|
database="user_db", collection="users", document=user_doc
|
|
)
|
|
print(f"Inserted user with ID: {user_id}")
|
|
|
|
# Multiple documents insert
|
|
products = [
|
|
{"name": "Laptop", "price": 999.99, "stock": 50},
|
|
{"name": "Mouse", "price": 29.99, "stock": 100},
|
|
{"name": "Keyboard", "price": 59.99, "stock": 75},
|
|
]
|
|
product_ids = mongodb.insert_many(
|
|
database="store_db", collection="products", documents=products
|
|
)
|
|
print(f"Inserted {len(product_ids)} products")
|
|
|
|
|
|
def find_examples() -> None:
|
|
"""Examples of find operations."""
|
|
# Find one document
|
|
user = mongodb.find_one(
|
|
database="user_db",
|
|
collection="users",
|
|
filter_query={"email": "john@example.com"},
|
|
projection={"username": 1, "email": 1, "_id": 0},
|
|
)
|
|
print(f"Found user: {user}")
|
|
|
|
# Find many with pagination
|
|
page_size = 10
|
|
page_number = 1
|
|
products = mongodb.find_many(
|
|
database="store_db",
|
|
collection="products",
|
|
filter_query={"price": {"$lt": 100}},
|
|
projection={"name": 1, "price": 1},
|
|
sort=[("price", 1)], # Sort by price ascending
|
|
limit=page_size,
|
|
skip=(page_number - 1) * page_size,
|
|
)
|
|
print(f"Found {len(products)} products under $100")
|
|
|
|
|
|
def update_examples() -> None:
|
|
"""Examples of update operations."""
|
|
# Update single document
|
|
result = mongodb.update_one(
|
|
database="store_db",
|
|
collection="products",
|
|
filter_query={"name": "Laptop"},
|
|
update_data={"price": 899.99, "stock": 45},
|
|
upsert=False,
|
|
)
|
|
print(f"Updated {result['modified_count']} laptop(s)")
|
|
|
|
# Update multiple documents
|
|
result = mongodb.update_many(
|
|
database="store_db",
|
|
collection="products",
|
|
filter_query={"stock": {"$lt": 10}},
|
|
update_data={"status": "low_stock"},
|
|
upsert=True,
|
|
)
|
|
print(f"Updated {result['modified_count']} low stock products")
|
|
|
|
|
|
def delete_examples() -> None:
|
|
"""Examples of delete operations."""
|
|
# Delete single document
|
|
count = mongodb.delete_one(
|
|
database="user_db",
|
|
collection="users",
|
|
filter_query={"email": "john@example.com"},
|
|
)
|
|
print(f"Deleted {count} user")
|
|
|
|
# Delete multiple documents
|
|
count = mongodb.delete_many(
|
|
database="store_db", collection="products", filter_query={"stock": 0}
|
|
)
|
|
print(f"Deleted {count} out-of-stock products")
|
|
|
|
|
|
def aggregate_examples() -> None:
|
|
"""Examples of aggregation operations."""
|
|
# Calculate average price by category
|
|
pipeline = [
|
|
{
|
|
"$group": {
|
|
"_id": "$category",
|
|
"avg_price": {"$avg": "$price"},
|
|
"total_products": {"$sum": 1},
|
|
}
|
|
},
|
|
{"$sort": {"avg_price": -1}},
|
|
]
|
|
results = mongodb.aggregate(
|
|
database="store_db", collection="products", pipeline=pipeline
|
|
)
|
|
print("Category statistics:", list(results))
|
|
|
|
|
|
def complex_query_example() -> None:
|
|
"""Example of a complex query combining multiple operations."""
|
|
# Find active users who made purchases in last 30 days
|
|
pipeline = [
|
|
{
|
|
"$match": {
|
|
"status": "active",
|
|
"last_purchase": {
|
|
"$gte": datetime.utcnow().replace(day=datetime.utcnow().day - 30)
|
|
},
|
|
}
|
|
},
|
|
{
|
|
"$lookup": {
|
|
"from": "orders",
|
|
"localField": "_id",
|
|
"foreignField": "user_id",
|
|
"as": "recent_orders",
|
|
}
|
|
},
|
|
{
|
|
"$project": {
|
|
"username": 1,
|
|
"email": 1,
|
|
"total_orders": {"$size": "$recent_orders"},
|
|
"total_spent": {"$sum": "$recent_orders.amount"},
|
|
}
|
|
},
|
|
{"$sort": {"total_spent": -1}},
|
|
]
|
|
results = mongodb.aggregate(
|
|
database="user_db", collection="users", pipeline=pipeline
|
|
)
|
|
print("Active users with recent purchases:", list(results))
|
|
|
|
|
|
if __name__ == "__main__":
|
|
# Example usage of all operations
|
|
insert_examples()
|
|
find_examples()
|
|
update_examples()
|
|
delete_examples()
|
|
aggregate_examples()
|
|
complex_query_example()
|