1. Limits and Skips with Sorts, Oh My!
In this lesson we will learn about the limit and skip parameters of Mongo queries. They can help us inspect a few documents at a time and page through a collection. In concert with sorting, they can help us get documents with extreme values.
2. Limiting our exploration
Let's say I want to get prize category and year information for a few prizes split three ways.
First, I check that for all prizes, either all laureates have a one-third share, or none have a one-third share. I verify my assumption with this for-loop of assertions.
Now, I can print information on prizes split three ways. I filter for laureate share equal to three, and I get a long iterator: tens of lines fill my screen. Can I fetch only a few documents to examine before I decide how to proceed next in my analysis? Yes.
Mongo provides a convenient limit option as an extra parameter to the find method. There we go.
3. Skips and paging through results
Besides limiting the number of results, we can also skip results server-side.
When you use the "skip" parameter in conjunction with limits,
you can get pagination, with the number of results per page set by the limit parameter.
4. Using cursor methods for {sort, skip, limit}
You can also chain methods to a cursor. This is an alternative to passing extra parameters to the "find" method.
Here's what this looks like in the case of setting limits. I don't pass "limit" as a keyword argument to the find method. Rather, I chain the limit method, with an argument of three, to the cursor.
And here's how to amend a cursor by chaining both skip and limit methods to it.
Finally, I can even alter the sorting on a cursor by chaining a call to the sort method. Here, I sort by ascending year.
5. Simpler sorts of sort
One last thing. When sorting using the chained method, pymongo allows a couple of shortcuts. Here we specify sorting as before with a list of (field, direction) pairs. There is only one pair because we are sorting by only one field.
In this case, we can destructure that single pair. Here I specify the sort with the field as the first argument and the direction as the second argument.
Furthermore, pymongo will take the default direction to be ascending. Thus, we can sort by ascending year as a chained call with a single argument, "year".
All these cursors yield the same sequence of documents.
Finally, note that using the "find_one" method is different. It's like a call to "find" with the limit set to one and with automatic fetching from the cursor. Thus, in this case, you cannot use cursor methods - you need to pass skip and sort requirements as arguments.
6. Limit or Skip Practice? Exactly.
Before you skip ahead, let's test some limits. Especially after getting some things sorted.