-
Notifications
You must be signed in to change notification settings - Fork 19
/
Copy pathone-to-one-join.py
133 lines (116 loc) · 3.25 KB
/
one-to-one-join.py
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
from pymongo import MongoClient
from datetime import datetime
uri = "<connection string>"
client = MongoClient(uri)
try:
agg_db = client["agg_tutorials_db"]
# start-colls
orders_coll = agg_db["orders"]
products_coll = agg_db["products"]
# end-colls
# start-insert-orders
orders_coll.delete_many({})
order_data = [
{
"customer_id": "elise_smith@myemail.com",
"orderdate": datetime(2020, 5, 30, 8, 35, 52),
"product_id": "a1b2c3d4",
"value": 431.43
},
{
"customer_id": "tj@wheresmyemail.com",
"orderdate": datetime(2019, 5, 28, 19, 13, 32),
"product_id": "z9y8x7w6",
"value": 5.01
},
{
"customer_id": "oranieri@warmmail.com",
"orderdate": datetime(2020, 1, 1, 8, 25, 37),
"product_id": "ff11gg22hh33",
"value": 63.13
},
{
"customer_id": "jjones@tepidmail.com",
"orderdate": datetime(2020, 12, 26, 8, 55, 46),
"product_id": "a1b2c3d4",
"value": 429.65
}
]
orders_coll.insert_many(order_data)
# end-insert-orders
# start-insert-products
products_coll.delete_many({})
product_data = [
{
"id": "a1b2c3d4",
"name": "Asus Laptop",
"category": "ELECTRONICS",
"description": "Good value laptop for students"
},
{
"id": "z9y8x7w6",
"name": "The Day Of The Triffids",
"category": "BOOKS",
"description": "Classic post-apocalyptic novel"
},
{
"id": "ff11gg22hh33",
"name": "Morphy Richardds Food Mixer",
"category": "KITCHENWARE",
"description": "Luxury mixer turning good cakes into great"
},
{
"id": "pqr678st",
"name": "Karcher Hose Set",
"category": "GARDEN",
"description": "Hose + nosels + winder for tidy storage"
}
]
products_coll.insert_many(product_data)
# end-insert-products
pipeline = []
# start-match
pipeline.append({
"$match": {
"orderdate": {
"$gte": datetime(2020, 1, 1, 0, 0, 0),
"$lt": datetime(2021, 1, 1, 0, 0, 0)
}
}
})
# end-match
# start-lookup
pipeline.append({
"$lookup": {
"from": "products",
"localField": "product_id",
"foreignField": "id",
"as": "product_mapping"
}
})
# end-lookup
# start-set
pipeline.extend([
{
"$set": {
"product_mapping": {"$first": "$product_mapping"}
}
},
{
"$set": {
"product_name": "$product_mapping.name",
"product_category": "$product_mapping.category"
}
}
])
# end-set
# start-unset
pipeline.append({"$unset": ["_id", "product_id", "product_mapping"]})
# end-unset
# start-run-agg
aggregation_result = orders_coll.aggregate(pipeline)
# end-run-agg
for document in aggregation_result:
print(document)
finally:
client.close()