Sort
The sort
filter allows you to sort the results of your query based on one or more fields. This filter is useful when you want to order the returned data in either ascending or descending order. Below is a detailed explanation of how to use the sort
filter in your API requests.
Basic Usage
The sort
filter is passed as a JSON object, where each key represents a field in your database, and the value indicates the sort order for that field.
{
"sort": {
"field1": 1,
"field2": -1
}
}
Sort Order
1
: Sorts the field in ascending order.-1
: Sorts the field in descending order.
Examples
Single Field Ascending
{
"sort": {
"createdAt": 1
}
}
This will return all records sorted by the createdAt
field in ascending order (oldest first).
Single Field Descending
{
"sort": {
"createdAt": -1
}
}
This will return all records sorted by the createdAt
field in descending order (newest first).
Multiple Fields
{
"sort": {
"status": 1,
"createdAt": -1
}
}
This will return all records sorted first by the status
field in ascending order, and within each status group, by the createdAt
field in descending order.
Notes
- The
sort
filter can be combined with other filters, such as thewhere
filter, to narrow down and order your results. - Sorting by multiple fields is particularly useful when you want to group and order data in a specific hierarchy.
Conclusion
The sort
filter is a powerful tool for ordering your query results. By specifying one or more fields and their respective sort orders, you can control how the data is presented, making it easier to work with large datasets.