MongoDB Aggregation $sort
Introduction
The $sort
stage in MongoDB's aggregation framework is used to sort the documents that pass through the pipeline according to specified fields. Sorting can be done in ascending or descending order, and it helps in organizing the data for further processing.
Prerequisites
MongoDB installed and running on your machine.
Access to
mongosh
and a populated database with sample data.
Step 1: Start mongosh
mongosh
Open Terminal/Command Prompt:
Launch your terminal (macOS/Linux) or command prompt (Windows).
Start
mongosh
:Type the following command and press Enter:
Step 2: Switch to the Database
Switch to the database where your collection is located.
Use a Database:
Step 3: Sample Data
Let’s assume you have a collection named sales
with documents that look like this:
Step 4: Using $sort
$sort
1. Basic Usage of $sort
$sort
To sort documents by a specific field, you can use the $sort
stage. For example, to sort the documents by item
in ascending order:
Output:
2. Sorting in Descending Order
To sort documents in descending order, use -1
. For instance, to sort the documents by quantity
in descending order:
Output:
3. Sorting by Multiple Fields
You can also sort by multiple fields. For instance, to sort by category
in ascending order and then by price
in descending order:
Output:
4. Using $sort
with Other Stages
$sort
with Other StagesYou can combine $sort
with other aggregation stages such as $match
and $limit
. For example, if you want to find the top 3 items with the highest quantity sold, you would first sort and then limit the results:
Output:
Conclusion
You have learned how to use the $sort
stage in MongoDB's aggregation framework to organize your data based on specified fields. Sorting data is crucial for analysis, reporting, and presentation, and the $sort
stage is essential for achieving this in aggregation pipelines.
Feel free to reach out if you have any questions or need further guidance!
Last updated