Skip to content

Commit 6d4ae60

Browse files
authored
Update 3. Get Only What You Need, and Fast.md
1 parent de1504d commit 6d4ae60

File tree

1 file changed

+36
-4
lines changed

1 file changed

+36
-4
lines changed

Introduction to MongoDB in Python/3. Get Only What You Need, and Fast.md

Lines changed: 36 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -137,7 +137,39 @@ The Nobel database is again available to you as db. We also pre-loaded a sample
137137

138138
---
139139
Complete the definition of all_laureates(prize). Within the body of the function:
140-
- [x] Sort the "laureates" list of the prize document according to the "surname" key.
141-
- [x] For each of the laureates in the sorted list, extract the "surname" field.
142-
- [x] The code for joining the last names into a single string is already written for you.
143-
- [x] Take a look at the console to make sure the output looks like what you'd expect!
140+
- [x] 1. Sort the "laureates" list of the prize document according to the "surname" key.
141+
- [x] 1. For each of the laureates in the sorted list, extract the "surname" field.
142+
- [x] 1. The code for joining the last names into a single string is already written for you.
143+
- [x] 1. Take a look at the console to make sure the output looks like what you'd expect!
144+
```py
145+
from operator import itemgetter
146+
147+
def all_laureates(prize):
148+
# sort the laureates by surname
149+
sorted_laureates = sorted(prize["laureates"], key=itemgetter("surname"))
150+
151+
# extract surnames
152+
surnames = [laureate['surname'] for laureate in sorted_laureates]
153+
154+
# concatenate surnames separated with " and "
155+
all_names = " and ".join(surnames)
156+
157+
return all_names
158+
159+
# test the function on a sample doc
160+
print(all_laureates(sample_prize))
161+
```
162+
- [x] 2. Find the documents for the prizes in the physics category, sort them in chronological order (by "year", ascending), and only fetch the "year", "laureates.firstname", and "laureates.surname" fields.
163+
```py
164+
# find physics prizes, project year and first and last name, and sort by year
165+
docs = db.prizes.find(
166+
filter= {"category": "physics"},
167+
projection= ['year', 'laureates.firstname', 'laureates.surname'],
168+
sort= [('year', 1)])
169+
```
170+
- [x] 3. Now that you have the prizes, and the function to extract laureates from a prize, print the year and the names of the laureates (use your all_laureates() function) for each prize document.
171+
```py
172+
# print the year and laureate names (from all_laureates)
173+
for doc in docs:
174+
print("{year}: {names}".format(year=doc['year'], names=all_laureates(doc)))
175+
```

0 commit comments

Comments
 (0)