0
0
MongoDBquery~30 mins

sort method ascending and descending in MongoDB - Mini Project: Build & Apply

Choose your learning style9 modes available
Sorting Documents with MongoDB sort Method
📖 Scenario: You are managing a small online bookstore database. You want to organize the books so customers can see them sorted by price, either from cheapest to most expensive or the other way around.
🎯 Goal: Build MongoDB queries that use the sort method to display books sorted by their price in ascending and descending order.
📋 What You'll Learn
Create a collection named books with the exact documents provided.
Create a variable sortAscending that holds the sorting order for ascending by price.
Create a variable sortDescending that holds the sorting order for descending by price.
Write a query using find() and sort(sortAscending) to get books sorted by price ascending.
Write a query using find() and sort(sortDescending) to get books sorted by price descending.
💡 Why This Matters
🌍 Real World
Sorting data is essential in databases to help users find information quickly, like showing products from cheapest to most expensive.
💼 Career
Database developers and data analysts often write queries to sort data efficiently for reports and user interfaces.
Progress0 / 4 steps
1
Create the books collection with sample data
Create a variable called books that is an array of documents with these exact entries: { title: "Book A", price: 15 }, { title: "Book B", price: 10 }, { title: "Book C", price: 20 }.
MongoDB
Need a hint?

Use an array of objects with the exact titles and prices given.

2
Define sorting order variables
Create a variable called sortAscending and set it to { price: 1 }. Then create a variable called sortDescending and set it to { price: -1 }.
MongoDB
Need a hint?

Use 1 for ascending and -1 for descending order in the sort object.

3
Write query to sort books by price ascending
Write a query called booksSortedAsc that uses books.find().sort(sortAscending) to get books sorted by price in ascending order.
MongoDB
Need a hint?

Use JavaScript array sort method to sort the books by price ascending.

4
Write query to sort books by price descending
Write a query called booksSortedDesc that uses books.find().sort(sortDescending) to get books sorted by price in descending order.
MongoDB
Need a hint?

Use JavaScript array sort method to sort the books by price descending.