Simplify your stack and build anything. Or everything.
Build tomorrow’s web with a modern solution you truly own.
Code-based nature means you can build on top of it to power anything.
It’s time to take back your content infrastructure.

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. In Local API multiple fields can be specified by using an array of strings. In REST API multiple fields can be specified by separating fields with comma. The minus symbol can be in front of individual fields.

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
}

To sort by multiple fields, you can use the sort option with fields in an array:

1
const getPosts = async () => {
2
const posts = await payload.find({
3
collection: 'posts',
4
sort: ['priority', '-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))

To sort by multiple fields, you can use the sort parameter with fields separated by comma:

1
fetch('https://localhost:3000/api/posts?sort=priority,-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