2.4 KiB
2.4 KiB
| title | aliases | tags | sources | created | updated | |||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|
| Queries — Sort |
|
|
|
2026-05-15 | 2026-05-15 |
Overview
Documents can be sorted by any top-level stored field. Prefix with - for descending order; no prefix = ascending.
Constraint: Virtual fields cannot be used for sorting unless wiki/payloadcms/fields-relationship. The field must exist in the database.
Performance: Enable
index: trueon fields you sort by. See wiki/payloadcms/database-indexes.
Local API
// Single field — ascending
const posts = await payload.find({
collection: 'posts',
sort: '-createdAt', // descending
})
// Multiple fields
const posts = await payload.find({
collection: 'posts',
sort: ['priority', '-createdAt'], // array of strings
})
REST API
GET /api/posts?sort=-createdAt
GET /api/posts?sort=priority,-createdAt // comma-separated
Using qs-esm query string builder (array form):
import { stringify } from 'qs-esm'
const query = stringify({ sort: ['priority', '-createdAt'] }, { addQueryPrefix: true })
fetch(`/api/posts${query}`)
GraphQL API
# Single field
query {
Posts(sort: "-createdAt") {
docs { color }
}
}
# Multiple fields — comma-separated string
query {
Posts(sort: "priority,-createdAt") {
docs { color }
}
}
Syntax Summary
| Context | Multiple fields | Descending prefix |
|---|---|---|
| Local API | Array of strings | -fieldName |
| REST API | Comma-separated string or array | -fieldName |
| GraphQL | Comma-separated string | -fieldName |
Key Takeaways
-fieldName= descending;fieldName= ascending — works across all three APIs- Local API accepts an array; REST/GraphQL accept a comma-separated string (REST also accepts array via qs)
- Only stored fields are sortable — virtual fields require a relationship link to be sortable
- Add
index: trueto sort fields for query performance; compound sorts benefit from compound indexes (see wiki/payloadcms/database-indexes) - Sort is complementary to wiki/payloadcms/queries-pagination and wiki/payloadcms/queries-select
Sources
raw/queries__sort.md— https://payloadcms.com/docs/queries/sort