MongoDB for Developers with Python Transcripts
Chapter: MongoDB's shell and native query syntax
Lecture: Concept: Sorting MongoDB results
0:01 Let's review sorting as a concept.
0:03 So there's a sort function right on the result set
0:05 on the cursor that comes back from find,
0:07 and the way it works is we pass it some prototypical json document;
0:11 but now instead of equality meaning matching,
0:14 it means tell me the thing and the direction that you want to sort.
0:17 So here we want to say sort all the books descending
0:21 show me the most recently published to the oldest, right,
0:25 show me the most recent books basically.
0:27 Now this works pretty well, we could put anything that has a direction
0:29 like a minus one, or one, I think you could even put higher multiples
0:33 like ten and 20, 50, -10, but use one and minus one, keep your sanity.
0:37 So this works well for one field, if we want to sort just by published,
0:40 but if I want to sort by one thing, and then another,
0:43 well we just put more into this document that we passed to sort,
0:46 so we're going to say sort by title ascending
0:49 and then sort by published descending,
0:51 we run this, we saw that we get the results in our demo,
0:54 first we sorted ascending by the title and any time they matched
0:59 we sorted descending by the publish date.
1:02 So first the 1994, A Nutshell Handbook, and then the 1993 one.