-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path4_indexes_and_aggregation.py
More file actions
152 lines (132 loc) · 4.07 KB
/
4_indexes_and_aggregation.py
File metadata and controls
152 lines (132 loc) · 4.07 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
from connection import get_database
from pymongo import ASCENDING, DESCENDING, TEXT
# Get database instance
db = get_database()
users = db.users
products = db.products
def index_operations():
"""Demonstrating MongoDB index operations"""
# Create a single field index
users.create_index([("email", ASCENDING)], unique=True)
print("Created unique index on email field")
# Create a compound index
users.create_index([
("age", ASCENDING),
("created_at", DESCENDING)
])
print("Created compound index on age and created_at fields")
# Create a text index for text search
users.create_index([("description", TEXT)])
print("Created text index on description field")
# List all indexes on a collection
print("\nCurrent indexes on users collection:")
for index in users.list_indexes():
print(index)
def basic_aggregation():
"""Demonstrating basic aggregation operations"""
# Calculate average age of users
pipeline = [
{
"$group": {
"_id": None,
"avgAge": {"$avg": "$age"},
"totalUsers": {"$sum": 1}
}
}
]
result = list(users.aggregate(pipeline))
print("\nAge statistics:", result)
# Group users by country and count
pipeline = [
{
"$group": {
"_id": "$address.country",
"userCount": {"$sum": 1}
}
},
{
"$sort": {"userCount": -1}
}
]
result = list(users.aggregate(pipeline))
print("\nUsers by country:", result)
def advanced_aggregation():
"""Demonstrating advanced aggregation operations"""
# Complex pipeline with multiple stages
pipeline = [
# Match stage - filter documents
{
"$match": {
"age": {"$gte": 18}
}
},
# Group stage - group and calculate
{
"$group": {
"_id": {
"country": "$address.country",
"premium": "$premium_member"
},
"count": {"$sum": 1},
"avgAge": {"$avg": "$age"}
}
},
# Sort stage
{
"$sort": {"count": -1}
},
# Project stage - reshape output
{
"$project": {
"_id": 0,
"country": "$_id.country",
"premium_status": "$_id.premium",
"user_count": "$count",
"average_age": {"$round": ["$avgAge", 1]}
}
}
]
result = list(users.aggregate(pipeline))
print("\nDetailed user statistics:", result)
def lookup_example():
"""Demonstrating $lookup operation (like JOIN in SQL)"""
# Find all orders and include user details
pipeline = [
{
"$lookup": {
"from": "users",
"localField": "user_id",
"foreignField": "_id",
"as": "user_details"
}
},
{
"$unwind": "$user_details"
},
{
"$project": {
"order_id": 1,
"amount": 1,
"user_name": "$user_details.name",
"user_email": "$user_details.email"
}
}
]
result = list(db.orders.aggregate(pipeline))
print("\nOrders with user details:", result)
if __name__ == "__main__":
print("=== Index Operations ===")
index_operations()
print("\n=== Basic Aggregation ===")
basic_aggregation()
print("\n=== Advanced Aggregation ===")
advanced_aggregation()
print("\n=== Lookup Example ===")
lookup_example()
"""
Documentation References:
- Indexes: https://www.mongodb.com/docs/manual/indexes/
- Aggregation Pipeline: https://www.mongodb.com/docs/manual/core/aggregation-pipeline/
- Aggregation Operators: https://www.mongodb.com/docs/manual/reference/operator/aggregation/
- $lookup: https://www.mongodb.com/docs/manual/reference/operator/aggregation/lookup/
"""