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
import type { Payload } from 'payload'
2
3
const getPosts = async (payload: Payload) => {
4
const posts = await payload.find({
5
collection: 'posts',
6
sort: '-createdAt',
7
})
8
9
return posts
10
}

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

1
import type { Payload } from 'payload'
2
3
const getPosts = async (payload: Payload) => {
4
const posts = await payload.find({
5
collection: 'posts',
6
sort: ['priority', '-createdAt'],
7
})
8
9
return posts
10
}

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