MongoDB Aggregation $sort

Welcome to TheCodingCollege.com, your go-to destination for coding tutorials and insights. In this article, we’ll explore the $sort stage in MongoDB’s aggregation pipeline. This essential feature helps you organize and analyze your data effectively.

What is the $sort Stage?

The $sort stage in MongoDB’s aggregation pipeline orders documents based on specified fields. Sorting is crucial for tasks like ranking, organizing datasets, and creating ordered views of data for analysis or display.

Syntax of $sort

The $sort stage has a straightforward syntax:

{ $sort: { <field1>: <order>, <field2>: <order>, ... } }
  • <field>: The field to sort by.
  • <order>: Use 1 for ascending order and -1 for descending order.

Example 1: Basic Sorting

Suppose you have a products collection:

[
  { "name": "Laptop", "price": 1200 },
  { "name": "Phone", "price": 800 },
  { "name": "Tablet", "price": 600 },
  { "name": "Monitor", "price": 300 }
]

Task: Sort the products by price in ascending order.

db.products.aggregate([
  { $sort: { price: 1 } }
])

Output:

[
  { "name": "Monitor", "price": 300 },
  { "name": "Tablet", "price": 600 },
  { "name": "Phone", "price": 800 },
  { "name": "Laptop", "price": 1200 }
]

Example 2: Sorting in Descending Order

Task: Sort the products by price in descending order.

db.products.aggregate([
  { $sort: { price: -1 } }
])

Output:

[
  { "name": "Laptop", "price": 1200 },
  { "name": "Phone", "price": 800 },
  { "name": "Tablet", "price": 600 },
  { "name": "Monitor", "price": 300 }
]

Example 3: Sorting by Multiple Fields

When sorting by multiple fields, MongoDB processes the fields in the specified order.

Task: Sort by price in ascending order and by name alphabetically.

db.products.aggregate([
  { $sort: { price: 1, name: 1 } }
])

Output:

[
  { "name": "Monitor", "price": 300 },
  { "name": "Tablet", "price": 600 },
  { "name": "Phone", "price": 800 },
  { "name": "Laptop", "price": 1200 }
]

Use Cases for $sort

  1. Ranking: Display top-performing products or employees.
  2. Pagination: Combine $sort with $skip and $limit for paginated results.
  3. Organized Data Display: Show data in ascending or descending order for dashboards or reports.

Best Practices for Using $sort

  • Index Fields Used in Sorting: Improve query performance by indexing the fields you sort on.
  • Combine with Other Stages: Use $match to filter data before sorting to reduce overhead.
  • Limit Output for Large Datasets: Combine $sort with $limit to process only necessary documents.

Real-World Application

E-commerce:

Task: Display the top 5 most expensive products.

db.products.aggregate([
  { $sort: { price: -1 } },
  { $limit: 5 }
])

This query ensures users see only the top 5 high-value products, improving their browsing experience.

Conclusion

The $sort stage in MongoDB’s aggregation pipeline is a powerful tool for organizing and analyzing data. Whether you’re working with e-commerce products, financial records, or user profiles, $sort allows you to create meaningful, ordered datasets.

Leave a Comment