Sort

Documents in Payload can be easily sorted by a specific Field. When querying Documents, you can pass the name of any top-level field, and the response will sort the Documents by that field in ascending order. If prefixed with a minus symbol ("-"), they will be sorted in descending order.

Because sorting is handled by the database, the field cannot be a Virtual Field. It must be stored in the database to be searchable.

Local API

To sort Documents in the Local API, you can use the sort option in your query:

1
const getPosts = async () => {
2
const posts = await payload.find({
3
collection: 'posts',
4
sort: '-createdAt',
5
})
6
7
return posts
8
}

REST API

To sort in the REST API, you can use the sort parameter in your query:

1
fetch('https://localhost:3000/api/posts?sort=-createdAt')
2
.then((response) => response.json())
3
.then((data) => console.log(data))

GraphQL API

To sort in the GraphQL API, you can use the sort parameter in your query:

1
query {
2
Posts(sort: "-createdAt") {
3
docs {
4
color
5
}
6
}
7
}
Next

Depth