-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlab2_mongo.py
More file actions
48 lines (36 loc) · 1.17 KB
/
Copy pathlab2_mongo.py
File metadata and controls
48 lines (36 loc) · 1.17 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
from pymongo import MongoClient
client = MongoClient('localhost', 27017)
db = client['store']
# Create collections
customers = db['customers']
orders = db['orders']
#reset collections
customers.drop()
orders.drop()
#insert documents
customers.insert_many([
{'customer_id': 1, 'name': 'Alice Smith', 'email': 'alicesmith@gmail.com'},
{'customer_id': 2, 'name': 'Bob Johnson', 'email': 'bobjohnson@gmail.com'}
])
orders.insert_many([
{'order_id': 1, 'customer_id': 1, 'product': {'name': 'Laptop', 'price': 999.99}, 'quantity': 1, 'order_date': '2023-10-01'},
{'order_id': 2, 'customer_id': 2, 'product': {'name': 'Smartphone', 'price': 499.99}, 'quantity': 2, 'order_date': '2023-10-02'}
])
print("\nFind one Customer:")
print(customers.find_one({'customer_id': 1}))
print("\nOrders for Bob Johnson:")
for order in orders.find({'customer_id': 2}):
print(order)
print("\nAggregate total revenue per customer:")
pipeline = [
{
"$group": {
"_id": "$customer_id",
"total_spent": {
"$sum": { "$multiply": ["$quantity", "$product.price"] }
}
}
}
]
for res in orders.aggregate(pipeline):
print(res)