To sort collection results by a collection field, pass the sort
argument to the <collection>Connection
query, with the value corresponding to the desired collection field to sort by. Results are returned in ascending order.
See reverse pagination for how to retrieve results in descending order.
To sort collection results by multiple fields, we need to define a multi-field "index" in our schema. An index definition determines which fields in a collection are included in the index and the order of the fields when sorting results.
In addition to determining the sort order of query results, indexes also impact query performance.
Here is an example index definition for our posts collection:
{collections: [{label: "Blog Posts",name: "post",path: "content/posts",format: "mdx",fields: [...],indexes: [{name: "category-date",fields: [{ name:"category" },{ name:"date" }]}]}]}
The name
property on the index definition is used when referencing it in the sort
argument. The fields
property is an ordered list of the fields from the collection that should be indexed, identified by the field name
. Results returned using the associated sort for this example would be first ordered by category
and then by date
.
If the sort
parameter is not specified in a query, results will be returned based on the default filename ordering.
Here we will query our post
collection with postConnection
and sort the results by the date
field:
{postConnection(sort: "date") {edges {node {idtitledate}}}}
{"data": {"postConnection": {"edges": [{"node": {"id": "content/posts/voteForPedro.json","title": "Vote For Pedro","date": "2022-06-15T07:00:00.000Z"}},{"node": {"id": "content/posts/anotherPost.json","title": "Just Another Blog Post","date": "2022-07-15T07:00:00.000Z"}},{"node": {"id": "content/posts/nested/anotherPost.json","title": "Just Another Blog Post","date": "2022-07-15T07:00:00.000Z"}}]}}}
Here we will query our post
collection with postConnection
and sort the results first by category
and then by date
using the multi-field index named category-date
:
{postConnection(sort: "category-date") {edges {node {idtitlecategorydate}}}}
{"data": {"postConnection": {"edges": [{"node": {"id": "content/posts/anotherPost.json","title": "Just Another Blog Post","category": "lifestyle","date": "2022-07-15T07:00:00.000Z"}},{"node": {"id": "content/posts/nested/anotherPost.json","title": "Just Another Blog Post","category": "lifestyle","date": "2022-07-15T07:00:00.000Z"}},{"node": {"id": "content/posts/voteForPedro.json","title": "Vote For Pedro","category": "politics","date": "2022-06-15T07:00:00.000Z"}}]}}}
Last Edited: August 15, 2024
© TinaCMS 2019–2024