Now we worked with cursors in the last lectures,
now there is something else we can do with the results this cursor stores or give us back to be
precise.
Now what can we do there? If I have a look at my movies and I find them all like this,
I get a bunch of movies obviously
and if I pretty print them, I well get them in a nicer form.
Now here please note I'm not handling the cursor manually,
I'll let the shell do that and let the shell fetch the first 20.
Now of course, a common operation would be that you want to sort the results you get back,
you can sort by anything, you can take a string and it will be sorted alphabetically or you can sort
by a number and then it will obviously be sorted by that number, let's say by rating.
Now we can sort by adding .sort if we use pretty, before pretty but always after find, now sort
takes a document where you describe how to sort.
Now here we could say we want to sort by the average rating, so rating.average and that already shows
us that we can also sort by a field in an embedded document, you could of course also sort by a top
level field.
So here we can sort by rating.average, now the value you specify here describes the direction in which
you sort, one means ascending, minus one means descending, so if I use minus one here,
I actually have the highest ratings first 8.8, 8.8
and if we scroll up a little bit further ahead, we see nine and so on
and of course as I mentioned, we can also sort in the opposite direction
and now we'll have the worse items first. Yor're also not limited to one sorting criteria,
you could say you want to sort by the rating first and the order does matter,
so it will first be sorted by rating
but then within each rating so to say, you want to sort by runtime, also ascending or descending so let's
say descending.
Now what we have this we have our ratings, 6.4, 6.4
but inside of that rating, it will actually sort by runtime.
Now here I have the same runtime, here
however I have 30 minutes in a 6.3 rating,
here again I have 6.3 with 60 minutes and hence, 60 minutes comes first before 30 because I'm sorting
the runtime in a descending order,
so higher values first.
So you can combine multiple, as many as you want sorting criteria here and sorting of course is a pretty
common task you do when you work with data because it allows you to not just narrow down the set of
data you want but then also retrieve it in the right order.
Now sort is available on this cursor,
it's not available for findOne for obvious reasons because findOne only gives you one document,
there is nothing to sort.