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}
]