0
0
MongoDBquery~30 mins

Sorting by multiple fields in MongoDB - Mini Project: Build & Apply

Choose your learning style9 modes available
Sorting Documents by Multiple Fields in MongoDB
📖 Scenario: You are managing a small online bookstore database. You want to organize the list of books so that customers can see the newest books first, and if two books have the same publication year, they should be sorted alphabetically by title.
🎯 Goal: Build a MongoDB query that sorts the books collection first by year in descending order, then by title in ascending order.
📋 What You'll Learn
Create a books collection with 5 documents containing title and year fields.
Define a variable sortOrder that specifies sorting by year descending and title ascending.
Write a query using find() and sort() with the sortOrder variable.
Assign the query result to a variable called sortedBooks.
💡 Why This Matters
🌍 Real World
Sorting data by multiple fields is common in databases to organize information clearly for users, such as sorting products by price and rating.
💼 Career
Database developers and data analysts often write queries that sort data by multiple criteria to prepare reports and improve user experience.
Progress0 / 4 steps
1
Create the books collection with sample data
Create a variable called books and assign it an array of 5 documents. Each document must have a title and a year field with these exact values: { title: 'The Hobbit', year: 1937 }, { title: '1984', year: 1949 }, { title: 'Brave New World', year: 1932 }, { title: 'Fahrenheit 451', year: 1953 }, { title: 'Animal Farm', year: 1945 }.
MongoDB
Need a hint?

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

2
Define the sorting order
Create a variable called sortOrder and assign it an object that sorts by year in descending order (use -1) and then by title in ascending order (use 1).
MongoDB
Need a hint?

Use an object with year: -1 and title: 1 to specify sorting order.

3
Write the query to sort the books
Create a variable called sortedBooks and assign it the result of calling db.books.find() followed by .sort(sortOrder) to sort the documents using the sortOrder variable.
MongoDB
Need a hint?

Use db.books.find().sort(sortOrder) to get sorted results.

4
Complete the sorting query setup
Ensure the sortedBooks variable holds the sorted cursor from db.books.find().sort(sortOrder). This completes the sorting by multiple fields.
MongoDB
Need a hint?

Make sure the sortedBooks variable is assigned the sorted query result.