Skip to main content

πŸ‘ Sorting

We can sort our results using the $sort stage. We need to sort on a field, with 1 being ascending and -1 descending order.

πŸ‘ Let's get all books from 1984, sorted by number of pages. We'll only show the title, pages, and authors.

[
{$match: {year: 1984}},
{$project: {_id: 0, title: 1, pages: 1, authors: 1}},
{$sort: {"pages": 1}},
]

As we can see, books with no pages info appear first. These documents don't have that information. Hence, pages is null and gets sorted as less than any number.

πŸ‘ We can sort the other way around:

[
{$match: {year: 1984}},
{$project: {_id: 0, title: 1, pages: 1, authors: 1}},
{$sort: {"pages": -1}},
]

πŸ‘ How can we get the thickest book from 1984?

Answer
[
{$match: {year: 1984}},
{$project: {_id: 0, title: 1, pages: 1, authors: 1}},
{$sort: {"pages": -1}},
{$limit: 1}
]