Sort Documents by a Single Field
In this step, you will learn how to sort documents in a MongoDB collection. Sorting allows you to organize query results in a specific order, which is crucial for data analysis and presentation. Your environment has been pre-configured with a bookstore database containing a books collection.
First, open the MongoDB shell to interact with the database. In your terminal, run the following command:
mongosh
Once inside the shell, switch to the bookstore database.
use bookstore
To see the documents in the books collection, you can use the find() method.
db.books.find();
Now, let's sort these documents. To sort by a single field, you chain the .sort() method to a find() query. The sort() method takes an object specifying the field to sort by and the direction: 1 for ascending and -1 for descending.
Let's sort the books by the number of pages in ascending order (from fewest to most pages).
db.books.find().sort({ pages: 1 });
You will see the book with the fewest pages, "Python Basics", listed first.
[
{
_id: ObjectId('...'),
title: 'Python Basics',
pages: 250,
price: 29.99
},
{
_id: ObjectId('...'),
title: 'MongoDB Fundamentals',
pages: 300,
price: 34.99
},
...
]
Next, let's sort the books by price in descending order to find the most expensive ones first.
db.books.find().sort({ price: -1 });
This command will display "Data Science" at the top, as it has the highest price.
[
{
_id: ObjectId('...'),
title: 'Data Science',
pages: 350,
price: 44.99
},
{
_id: ObjectId('...'),
title: 'JavaScript Advanced',
pages: 400,
price: 39.99
},
...
]