Skip to content

Commit f2f2503

Browse files
authored
Update 4. Aggregation Pipelines: Let the Server Do It For You.md
1 parent 71222a5 commit f2f2503

File tree

1 file changed

+16
-0
lines changed

1 file changed

+16
-0
lines changed

Introduction to MongoDB in Python/4. Aggregation Pipelines: Let the Server Do It For You.md

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -81,3 +81,19 @@ Possible Answers
8181
- [ ] "laureates.share", ["3"], ["3"], "laureates.share"
8282
- [ ] "laureates.share", {"3"}, {"3"}, "laureates.share"
8383
- [ ] "$laureates.share", {"3"}, {"3"}, "$laureates.share"
84+
## 🦍 Organizing prizes
85+
In the slides at the beginning of this lesson, we saw a two-stage aggregation pipeline to determine the number of prizes awarded in total. How many prizes were awarded (at least partly) to organizations?
86+
- [x] Fill out pipeline to determine the number of prizes awarded (at least partly) to organizations. To do this, you'll first need to $match on the "gender" that designates organizations.
87+
- [x] Then, use a field path to project the number of prizes for each organization as the "$size" of the "prizes" array. Recall that to specify the value of a field "<my_field>", you use the field path "$<my_field>".
88+
- [x] Finally, use a single group {"_id": None} to sum over the values of all organizations' prize counts.
89+
```py
90+
# Count prizes awarded (at least partly) to organizations as a sum over sizes of "prizes" arrays.
91+
pipeline = [
92+
{"$match": {"gender": "org"}},
93+
{"$project": {"n_prizes": {"$size": "$prizes"}}},
94+
{"$group": {"_id": None, "n_prizes_total": {"$sum": "$n_prizes"}}}
95+
]
96+
97+
print(list(db.laureates.aggregate(pipeline)))
98+
```
99+
[{'_id': None, 'n_prizes_total': 27}]

0 commit comments

Comments
 (0)