Skip to content

Commit 95162f6

Browse files
authored
Update 3. Get Only What You Need, and Fast.md
1 parent 8305637 commit 95162f6

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed

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

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -261,3 +261,44 @@ Possible Answers
261261
- [x] 5: the second call to limit overrides the first
262262
- [ ] none: instead, an error is raised
263263
> reason : You can think of the query parameters as being updated like a dictionary in Python: `d = {'limit': 3}; d.update({'limit': 5}); print(d) will print "{'limit': 5}"`
264+
265+
## 🦍 The first five prizes with quarter shares
266+
- [x] Save to filter_ the filter document to fetch only prizes with one or more quarter-share laureates, i.e. with a "laureates.share" of "4".
267+
- [x] Save to projection the list of field names so that prize category, year and laureates' motivations ("laureates.motivation") may be fetched for inspection.
268+
- [x] Save to cursor a cursor that will yield prizes, sorted by ascending year. Limit this to five prizes, and sort using the most concise specification.
269+
```py
270+
from pprint import pprint
271+
272+
# Fetch prizes with quarter-share laureate(s)
273+
filter_ = {'laureates.share': '4'}
274+
275+
# Save the list of field names
276+
projection = ['category', 'year', 'laureates.motivation']
277+
278+
# Save a cursor to yield the first five prizes
279+
cursor = db.prizes.find(filter_, projection).sort('year').limit(5)
280+
pprint(list(cursor))
281+
```
282+
## 🦍 Pages of particle-prized people
283+
- [x] Complete the function get_particle_laureates that, given page_number and page_size, retrieves a given page of prize data on laureates who have the word "particle" (use $regex) in their prize motivations ("prizes.motivation"). Sort laureates first by ascending "prizes.year" and next by ascending "surname".
284+
- [x] Collect and save the first nine pages of laureate data to pages.
285+
```py
286+
from pprint import pprint
287+
288+
# Write a function to retrieve a page of data
289+
def get_particle_laureates(page_number=1, page_size=3):
290+
if page_number < 1 or not isinstance(page_number, int):
291+
raise ValueError("Pages are natural numbers (starting from 1).")
292+
particle_laureates = list(
293+
db.laureates.find(
294+
{"prizes.motivation": {"$regex": "particle"}},
295+
["firstname", "surname", "prizes"])
296+
.sort([("prizes.year", 1), ("surname", 1)])
297+
.skip(page_size * (page_number - 1))
298+
.limit(page_size))
299+
return particle_laureates
300+
301+
# Collect and save the first nine pages
302+
pages = [get_particle_laureates(page_number=page) for page in range(1,9)]
303+
pprint(pages[0])
304+
```

0 commit comments

Comments
 (0)