Ordering Query Results
Part of the Databases with MongoDB section of Coddy's Node.js journey. Lesson 11 of 29.
A database query can return books in the order your page needs. Add sort to the cursor before toArray. Its object names the field and direction: 1 means ascending, and -1 means descending.
await books.find().sort({year: 1}).toArray();
// Emma (1815), Dune (1965), Kindred (1979)Ascending years put the oldest book first. Descending years put the newest first. Sorting changes the order of results, not the fields inside each document. Keep the filter empty while you practise ordering. The next step will keep only the first few results.
Challenge
EasyThis is a small practice project. Its setup is provided; edit only exercise.js.
Return all books sorted by year, newest first. Run and GET /result: Kindred, Dune, Emma, in that order.
Try it yourself
export async function exercise(books) {
return await books.find().toArray();
}
All lessons in Databases with MongoDB
Practice on your own: Express playground