Docs

Querying documents

Filter collections by any field with AND / OR, query every subcollection with the same name (collection groups), sort, page with cursors, count, sum and average matches, and index what you query.

Updated Oct 23, 2026

A query reads one collection (or subcollection, like users/alice/posts) and returns the documents whose fields match its filters, in the order you ask for. It runs in your project's Postgres as the caller, so collection rules and row policies decide exactly what each user gets back — the same as reading one document.

POST _querySQL as the callerYour appwhere · orderBy ·limit · cursorGatewayauth · rate limit· readAccess policiesdoc:read on thecollectionProject Postgressov_documents ·row policies ·indexes
Values are always bound parameters; field paths and the collection are quoted by the database driver so Postgres can use your indexes.

#Filters

OperatorMatches documents where the field…
==, !=equals / exists and does not equal the value
<, <=, >, >=compares with the value — only values of the same type match ("1999" is not > 1900)
in, not-inequals one of / exists and equals none of up to 30 values
array-containsis an array holding the value (objects must match exactly)
array-contains-anyis an array holding at least one of up to 30 values
  • Use dotted paths for nested fields: address.city. A key with other characters goes in backticks: `meta.first-seen
  • The document id is __key__: where("__key__", "in", ["a", "b"]).
  • Ordering by a field leaves out documents that don't have it. Ties are broken by document id.
  • Up to 30 filters and 8 order-by fields per query; limit up to your plan's documents per query.

#OR and nested filters

Filters are combined with AND. For OR, put a group in where: or(…) matches documents that match any of its filters, and and(…) nests inside it — the same as Firestore's or() / and(). Groups nest up to 4 levels, and a query can expand to at most 30 OR terms (an AND of two 6-filter ORs is 36, so it is refused). Over HTTP a group is {"or": [...]} or {"and": [...]}.

import { or, and, filter } from '@sovaria/sdk'

// status is open AND (priority >= 3 OR (assignee is me AND due this week))
const tasks = await sov.collection('tasks')
  .where('status', '==', 'open')
  .where(or(filter('priority', '>=', 3), and(filter('assignee', '==', uid), filter('due', '<', weekEnd))))
  .get()

// Firestore code works unchanged
import { query, where, or, getDocs } from '@sovaria/sdk/firestore'
await getDocs(query(collection(db, 'tasks'), or(where('priority', '>=', 3), where('pinned', '==', true))))

#Collection groups

A collection group reads every collection with the same id at any depth, like Firestore's collectionGroup: comments covers comments, posts/p1/comments and users/u1/posts/p9/comments. Filters, sorting, cursors, count and aggregations work the same; in a group the document identity (__key__, the tiebreak and cursors) is the full document path, so two comments/a under different parents never collide.

const flagged = await sov.collectionGroup('comments')
  .where('flagged', '==', true).orderBy('at', 'desc').limit(50).get()
flagged.docs.forEach((d) => console.log(d.path))   // posts/p1/comments/c7, users/u2/comments/c1, …
const next = await sov.collectionGroup('comments').where('flagged', '==', true)
  .orderBy('at', 'desc').limit(50).startAfter(flagged.docs.at(-1)).get()

// Firestore code works unchanged
import { collectionGroup, query, where, getDocs } from '@sovaria/sdk/firestore'
await getDocs(query(collectionGroup(db, 'comments'), where('flagged', '==', true)))

Who sees what. Your collection rules are checked once per collection *pattern* in the group, with document ids written as * — the same patterns you use in rules (posts/*/comments). A pattern your rules refuse is checked again per concrete collection (posts/p1/comments, up to 50), and whatever is still refused is left out of the results. A pattern your rules allow is also checked per concrete collection, so a rule that denies one sub-collection (posts/p1/comments) is honoured; up to 500 concrete collections are checked per query, and any past that are left out rather than read unchecked (the answer then has scope_truncated: true and collections_unchecked). The answer's collections_skipped says how many collections were left out. If nothing in the group is readable the query is refused with 403. Row policies apply to every document as usual. Rules can tell a group read apart: it is checked with the pattern as the resource and collection_group set in the data-access context.

  • For speed, the first group query builds a group index on every project (in the background, without blocking writes; it doesn't count toward your plan's indexes). For sorting or ranges over a large group, create a composite index with scope collection_group — the index_hint says so.
  • Live listeners work on groups too: sov.collectionGroup('comments').onSnapshot(…) gets every added, modified and removed comment under any parent, keyed by path. Renewing a listener checks your rules per pattern again, so collections a user loses access to drop out.
  • Offline, the SDK answers group queries from every cached collection with that id.

#Count, sum and average

Aggregations run in your project's Postgres and return only the numbers, so they cost one query however many documents match. Ask for up to 5 at once. sum and average use numeric values only (other types are skipped, like Firestore); average is null when no matching document has a number there. With limit, they cover the first limit results in orderBy order; without, every match. The same rules and row policies apply as for reading the documents, and every field you aggregate counts as read.

import { count, sum, average } from '@sovaria/sdk'

const { n, revenue, avgOrder } = await sov.collection('orders')
  .where('status', '==', 'paid')
  .aggregate({ n: count(), revenue: sum('total'), avgOrder: average('total') })

// Firestore code works unchanged
import { getAggregateFromServer, sum as fsum } from '@sovaria/sdk/firestore'
const snap = await getAggregateFromServer(query(collection(db, 'orders')), { revenue: fsum('total') })
snap.data().revenue

Offline, the SDK answers aggregations from its cache (marked from_cache), like queries. For grouping (GROUP BY) and anything beyond count, sum and average, use SQL over the collection — see the next section.

const orders = sov.collection('orders')
const page = await orders
  .where('status', '==', 'paid')
  .where('total', '>=', 50)
  .orderBy('total', 'desc')
  .limit(20)
  .get()
page.docs.forEach((d) => console.log(d.id, d.data, d.version))

// Next page: pass the last snapshot (or page.nextCursor)
const next = await orders.where('status', '==', 'paid').where('total', '>=', 50)
  .orderBy('total', 'desc').limit(20).startAfter(page.docs.at(-1)).get()

const howMany = await orders.where('status', '==', 'paid').count()

#Cursors and pages

startAt / startAfter / endAt / endBefore take either a document snapshot (or {"key": "id"} over HTTP — the server reads that document, as you, for its values) or the values of the order-by fields in order, optionally followed by the document id. limitToLast(n) returns the last n in the same order. Every answer says has_more and gives next_cursor for the next page.

#Join documents with tables in SQL

Documents and tables live in the same project database, so SQL can read a collection next to your tables with sov_collection('<collection>'). It returns one row per document — id, data (the JSON), version, owner_id, created_at, updated_at — for the environment you call from. Subcollections work too: sov_collection('users/u1/orders'). Neither Firebase nor Supabase can join their document data with relational tables in one query.

-- Orders (a table) with each customer's name (a document)
SELECT o.id, o.total, c.data->>'name' AS customer, c.data->'address'->>'city' AS city
  FROM orders o
  JOIN sov_collection('customers') c ON c.id = o.customer_id
 WHERE o.created_at > now() - interval '7 days';

-- Documents only: aggregate a collection with SQL
SELECT data->>'plan' AS plan, count(*) FROM sov_collection('accounts') GROUP BY 1;
  • Access is checked the same way as a query through the documents API: the collection needs doc:read in your collection rules (or, for app users, the row policies on sov_documents decide), and every table needs its SQL rule. A collection name must be a string literal, so it can be checked before the statement runs.
  • Row security on documents still applies inside SQL: each user only gets the documents your row policies let them read.
  • It is read-only. Write documents with the documents API so versions, transforms, triggers and listeners keep working.
  • Postgres inlines the function, so filters on id use the documents index; for filters on fields inside data, add a document index (below) or an expression index.

#Indexes

Equality and array filters use the document table's JSON index on every project. For sorting and ranges, Sovaria indexes the first order-by or range field automatically once a collection has 1,000 documents. Queries that combine several fields run fastest on a composite index: the answer's index_hint names it, and Collections › Indexes (or the API) creates it in the background without blocking writes.

await sov.data.createDocIndex('orders', ['status', { path: 'total', order: 'desc' }])
const { indexes, limit } = await sov.data.docIndexes('orders')   // state: building | ready | failed

Creating and dropping indexes is for project team members and the service key. A query slower than your plan's statement timeout returns 504 DEADLINE_EXCEEDED with the index that would help.

#In the console

  • Collections › Query: build filters and sorting, run, load more, and export the results as JSON, JSON Lines or CSV.
  • Collections › Indexes: every automatic and composite index with its state and size, and your plan's cap.
  • Collections › Data: large collections load 100 documents at a time; import JSON, JSON Lines or CSV (dotted headers become nested fields).

#Plan limits

LimitFreeProUltraTeamEnterprise
Documents per query (nosql.max_scan_rows)1,0005,00010,00025,00050,000
Document indexes per project (docs.max_indexes)101003001,0005,000
Query timeout (sql.statement_timeout_ms)3 s8 s15 s30 s60 s

#Coming from Firebase or Supabase?

PlatformWhat this is called there
FirebaseFirestore queries (where, orderBy, limit, collectionGroup)
SupabaseSupabase filters (PostgREST)
SovariaQuerying documents

Moving an existing app? Migrate from Supabase or Firebase imports users (with their passwords), data, files and rules.