π 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.
- Atlas UI
- MongoDB Shell
[
{$match: {year: 1984}},
{$project: {_id: 0, title: 1, pages: 1, authors: 1}},
{$sort: {"pages": 1}},
]
let booksFrom1984 = {$match: {year: 1984}};
let showOnlyTheseFields = {$project: {_id: 0, title: 1, pages: 1, authors: 1}};
let slimmerBooksFirst = {$sort: {"pages": 1}}
db.books.aggregate([
booksFrom1984,
showOnlyTheseFields,
slimmerBooksFirst,
]);
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:
- Atlas UI
- MongoDB Shell
[
{$match: {year: 1984}},
{$project: {_id: 0, title: 1, pages: 1, authors: 1}},
{$sort: {"pages": -1}},
]
let booksFrom1984 = {$match: {year: 1984}};
let showOnlyTheseFields = {$project: {_id: 0, title: 1, pages: 1, authors: 1}};
let thickerBooksFirst = {$sort: {"pages": -1}}
db.books.aggregate([
booksFrom1984,
showOnlyTheseFields,
thickerBooksFirst,
]);
π How can we get the thickest book from 1984?
Answer
- Atlas UI
- MongoDB Shell
[
{$match: {year: 1984}},
{$project: {_id: 0, title: 1, pages: 1, authors: 1}},
{$sort: {"pages": -1}},
{$limit: 1}
]
let booksFrom1984 = {$match: {year: 1984}};
let showOnlyTheseFields = {$project: {_id: 0, title: 1, pages: 1, authors: 1}};
let thickerBooksFirst = {$sort: {"pages": -1}}
let justOne = {$limit: 1}
db.books.aggregate([
booksFrom1984,
showOnlyTheseFields,
thickerBooksFirst,
justOne
]);