Now that we had a look at the basics of indexes,
it's also important to understand that indexes are not just there for finding but they can also help
you with sorting because we have a sorted list of elements of the index right,
mongodb can utilize that in case you want to sort in the same way that index list is sorted.
So in our example here, I could find, whoops and I should explain this of course, so I could find let's
say all people with an age of 35 and then sort with that sort
operator and then sort for gender in an ascending order.
If I execute this, you see that it did actually use an index scan for both gender and age,
even though I only filtered by age but it used the gender information for the sorting.
Now this is another cool feature of indexes, since we have an ordered list of values already, mongodb
can utilize that to quickly give us back the order of documents we need.
Now also important to understand or to know here is that if you are not using indexes and you do a sort
on a large amount of documents, you can actually timeout because mongodb has a threshold of
32 megabytes in memory for sorting
and if you have no index, mongodb will essentially fetch all your documents into memory and do the
sort there
and for large collections and large amounts of fetched documents, this can simply be too much to then
sort.
So sometimes, you also need an index not just to speed up the query which always makes sense but also
to be able to sort at all.
Now this is not the case for our small dataset here but if you have millions of documents, you could
very well have a query where you fetch so many documents that an in-memory sort which is the default
then is just not possible and you need an index which is already sorted
so that mongodb doesn't have to sort in memory but can just take the order you have in the index.
So that's also something important to keep in mind that when you're sorting documents and you have
a lot of documents at a given query, you might need an index to be able to sort them at all because
mongodb has this threshold of 32 megabytes which it reserves in memory for the fetched documents
and sorting them.