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