obsidian/raw/_processed/queries__select.md
2026-05-15 16:34:07 +01:00

7.8 KiB

title label order desc keywords source
Select Select 30 Payload select determines which fields are selected to the result. query, documents, pagination, documentation, Content Management System, cms, headless, javascript, node, react, nextjs https://payloadcms.com/docs/queries/select

By default, Payload's APIs will return all fields for a given collection or global. But, you may not need all of that data for all of your queries. Sometimes, you might want just a few fields from the response.

With the Select API, you can define exactly which fields you'd like to retrieve. This can impact the performance of your queries by affecting the load on the database and the size of the response.

Local API

To specify select in the Local API, you can use the select option in your query:

import type { Payload } from 'payload'

// Include mode - result type will only contain: id, text, group.number, and array
const getPosts = async (payload: Payload) => {
  const posts = await payload.find({
    collection: 'posts',
    // highlight-start
    select: {
      text: true,
      // select a specific field from group
      group: {
        number: true,
      },
      // select all fields from array
      array: true,
    },
    // highlight-end
  })

  return posts
}

// Exclude mode - result type will contain all fields except: array and group.number
const getPosts = async (payload: Payload) => {
  const posts = await payload.find({
    collection: 'posts',
    // Select everything except for array and group.number
    // highlight-start
    select: {
      array: false,
      group: {
        number: false,
      },
    },
    // highlight-end
  })

  return posts
}

Empty select

The id field is always included in the result, regardless of your select query. If you pass an empty select object, only the id will be returned:

const post = await payload.findByID({
  collection: 'posts',
  id: '1',
  select: {},
})

console.log(post) // { id: '1' }
**Important:** To perform querying with `select` efficiently, Payload implements your `select` query on the database level. Because of that, your `beforeRead` and `afterRead` hooks may not receive the full `doc`. To ensure that some fields are always selected for your hooks / access control, regardless of the `select` query you can use the [entity-level `select`](#entity-level-select-config) function on your Collection or Global config.

Entity-level select config

Both Collections and Globals accept a top-level select function that runs before every read and lets you transform the caller's select based on request context. It receives { operation, req, select } and returns the final select to apply, replacing the caller's. Return undefined to leave the caller's select untouched.

Common uses:

  • Force a field to always be populated so it's available in hooks / access control.
  • Differentiate API requests from admin panel requests to optimize payload size.
import type { CollectionConfig } from 'payload'

export const Posts: CollectionConfig = {
  slug: 'posts',
  // Always include `title`, regardless of the caller's `select`.
  select: ({ select }) => (select ? { ...select, title: true } : undefined),
  fields: [
    // ...
  ],
}

The function form replaces the caller's select rather than deep-merging, so spread the caller's select into your returned object when you want to add to it instead of replacing it. Per-document data is not available — this runs before the read.

REST API

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

fetch(
  // highlight-start
  'https://localhost:3000/api/posts?select[color]=true&select[group][number]=true',
  // highlight-end
)
  .then((res) => res.json())
  .then((data) => console.log(data))

To understand the syntax, you need to understand that complex URL search strings are parsed into a JSON object. This one isn't too bad, but more complex queries get unavoidably more difficult to write.

For this reason, we recommend to use the extremely helpful and ubiquitous qs-esm package to parse your JSON / object-formatted queries into query strings:

import { stringify } from 'qs-esm'
import type { Where } from 'payload'

const select: Where = {
  text: true,
  group: {
    number: true,
  },
  // This query could be much more complex
  // and QS would handle it beautifully
}

const getPosts = async () => {
  const stringifiedQuery = stringify(
    {
      select, // ensure that `qs` adds the `select` property, too!
    },
    { addQueryPrefix: true },
  )

  const response = await fetch(
    `http://localhost:3000/api/posts${stringifiedQuery}`,
  )
  // Continue to handle the response below...
}
**Reminder:** This is the same for [Globals](../configuration/globals) using the `/api/globals` endpoint.

defaultPopulate collection config property

The defaultPopulate property allows you specify which fields to select when populating the collection from another document. This is especially useful for links where only the slug is needed instead of the entire document.

With this feature, you can dramatically reduce the amount of JSON that is populated from Relationship or Upload fields.

For example, in your content model, you might have a Link field which links out to a different page. When you go to retrieve these links, you really only need the slug of the page.

Loading all of the page content, its related links, and everything else is going to be overkill and will bog down your Payload APIs. Instead, you can define the defaultPopulate property on your Pages collection, so that when Payload "populates" a related Page, it only selects the slug field and therefore returns significantly less JSON:

import type { CollectionConfig } from 'payload'

// The TSlug generic can be passed to have type safety for `defaultPopulate`.
// If avoided, the `defaultPopulate` type resolves to `SelectType`.
export const Pages: CollectionConfig<'pages'> = {
  slug: 'pages',
  // Specify `select`.
  defaultPopulate: {
    slug: true,
  },
  fields: [
    {
      name: 'slug',
      type: 'text',
      required: true,
    },
  ],
}

**Important:** When using `defaultPopulate` on a collection with [Uploads](/docs/fields/upload) enabled and you want to select the `url` field, it is important to specify `filename: true` as well, otherwise Payload will not be able to construct the correct file URL, instead returning `url: null`.

Populate

Setting defaultPopulate will enforce that each time Payload performs a "population" of a related document, only the fields specified will be queried and returned. However, you can override defaultPopulate with the populate property in the Local and REST API:

Local API:

import type { Payload } from 'payload'

const getPosts = async (payload: Payload) => {
  const posts = await payload.find({
    collection: 'posts',
    populate: {
      // Select only `text` from populated docs in the "pages" collection
      // Now, no matter what the `defaultPopulate` is set to on the "pages" collection,
      // it will be overridden, and the `text` field will be returned instead.
      pages: {
        text: true,
      }, // highlight-line
    },
  })

  return posts
}

REST API:

fetch('https://localhost:3000/api/posts?populate[pages][text]=true') // highlight-line
  .then((res) => res.json())
  .then((data) => console.log(data))