#only return certain columns

3 messages · Page 1 of 1 (latest)

sweet horizon
#

is it possible to only get back certain columns instead of the whole object with a query

static masonBOT
#

Hi @sweet horizon. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:

#

Based on the knowledge sources provided, Convex queries currently do not support selecting or projecting specific fields from documents. Queries in Convex return whole documents by default.

As mentioned in the Discord support thread:

How to tell the query to include specific fields

A Convex staff member stated:

"Queries (ctx.db.query) can only return whole documents, you can map after retrieving the documents."

To get only certain fields, you would need to retrieve the full documents and then map or transform the results after the query. For example:

export default query(async (ctx) => {
  const results = await ctx.db.query("people").collect();
  return results.map((person) => ({ 
    nameFirst: person.name_first 
  }));
});

While this may seem inefficient compared to SQL-style projections, Convex is designed to be very fast by default. The Convex team encourages developers to focus on outcomes and not worry about performance unless there's a specific problem.

If you have concerns about efficiency or need to frequently access only a subset of fields from large documents, you might consider splitting your data into separate tables, as suggested in another Discord thread:

efficiency of: return (await ctx.db.query("messages").collect()).length;

However, this approach has its own trade-offs and may not be suitable for all use cases.

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: