#Is Or filtering supported in convex?

3 messages · Page 1 of 1 (latest)

tribal drift
#

I have a schema like this

 workspace: defineTable({
    name: v.string(),
    slug: v.string(),
    createdBy: v.id("users"),
    updatedBy: v.optional(v.id("users")),
  })
    .index("by_createdBy", ["createdBy"])
    .index("by_name", ["name"])
    .index("by_slug", ["slug"])

Is it possible to query a workspace by id or slug whichever matches kinda like a OR filter in SQL?

grand dawnBOT
#

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

#

Yes, Convex supports or filtering using the q.or operator in its filter builder. You can construct queries that match documents where at least one of several conditions is true.

For your schema, if you want to query a workspace by either id or slug, you can use the .filter method with q.or. Here’s how you might write such a query:

const result = await ctx.db
  .query("workspace")
  .filter(q =>
    q.or(
      q.eq(q.field("_id"), yourIdValue),
      q.eq(q.field("slug"), yourSlugValue)
    )
  )
  .collect();

This will return all workspaces where either the _id matches yourIdValue or the slug matches yourSlugValue — just like an SQL OR filter.

Note: This type of filter will scan the entire table unless you use an index that covers both fields, which is not possible in Convex (an index is on a specific ordered set of fields). So, while the filter is supported, it may not be as efficient as an indexed query, especially for large tables. For best performance, use indexed fields for filtering whenever possible, but for this specific "OR" use case, a table scan is required unless you split the query and merge results in your application code.

References:


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