Skip to main content

Access document data with SQL

The usual entry points for pgdoc are the document database SDK and HTTP API, with the same calling convention as before migration. The data itself lives in PostgreSQL, so you can also read and write it directly inside the instance with SQL, putting document data and relational data into a single query.

This page applies when pgdoc is already enabled and you need batch operations, cross-table analysis, or data export. For basic reads and writes, permissions, and index configuration, see Using pgdoc.

Prerequisites​

Get the database parameter​

The first parameter of pgdoc functions is database, which names the document store that holds the data. Query the instance to find the available values:

SELECT DISTINCT database_name FROM pgdoc_catalog.collections;

Pass the value you find as the first argument to every function. If several rows come back, choose the store that holds your target collections. Examples below write it as {database}; replace it with the actual value.

⚠️ Note: A wrong value does not raise an error — it silently returns empty results, such as an empty collection or a count of 0, which is hard to diagnose. Confirm it again after switching environments or instances.

Two SQL entry points​

Entry pointTypical functionsCharacteristics
Imperative APIpgdoc.find_cursor_first_page, pgdoc.aggregate_cursor_first_pageParameters match document database commands; supports indexes, cursors, and aggregation pipelines; reads and writes
Collection functionpgdoc.collectionTreats a collection as a table for standard SQL filtering, grouping, and joins; read-only

Both read the same data. Choose by scenario:

ScenarioRecommended entry point
Exact lookup by _id or an indexed field, paged traversalImperative API
Inserts, updates, deletesImperative API
Joins with relational tables, UNION across collections, window functionspgdoc.collection
Data export, offline analysispgdoc.collection

Calling conventions​

Constructing and restoring BSON​

Parameters of the imperative API are BSON. Build them from JSON text with pgdoc_core.bson_json_to_bson(), and turn return values back into readable text with pgdoc_core.bson_to_json_string().

-- JSON text to BSON
SELECT pgdoc_core.bson_json_to_bson('{"count":"users"}');

-- BSON back to Extended JSON
SELECT pgdoc_core.bson_to_json_string(
pgdoc_core.bson_json_to_bson('{"a":1}')
)::text;
-- { "a" : { "$numberInt" : "1" } }

💡 Tip: Restored numbers carry type wrappers such as $numberInt, $numberLong, $date, and $oid. This is how the Extended JSON specification represents values.

Match the call style to the return type​

The SQL style depends on the function's return type. Mixing them raises column "p_success" does not exist:

Return typeTypical functionsCall style
recordinsert, update, delete, find_cursor_first_pageSELECT column FROM pgdoc.xxx(...)
bsoncount_query, distinct_query, coll_statsSELECT pgdoc_core.bson_to_json_string(pgdoc.xxx(...))::text
boolean / voidcreate_collection, drop_collection, rename_collectionSELECT pgdoc.xxx(...)
procedureinsert_bulk, drop_indexesCALL pgdoc.xxx(...)

One statement per request​

Each request may execute only one statement. Multi-statement input such as SET ...; SELECT ... returns DATABASE_42601.

Query collections with pgdoc.collection​

pgdoc.collection() maps a collection to a table, which is the entry point that connects document data with relational data.

Returned columns​

SELECT * FROM pgdoc.collection('{database}', 'users') LIMIT 10;
ColumnTypeDescription
shard_key_valuebigintInternal collection identifier; usually not of interest
object_idbsonThe document _id, stored as single-key BSON
documentbsonFull document content

Extract fields​

Use pgdoc_core.bson_get_value_text() to read a scalar by path. It costs less than converting whole documents to JSON, and paths support dot notation for nested fields:

SELECT pgdoc_core.bson_get_value_text(document, 'name') AS name,
pgdoc_core.bson_get_value_text(document, 'profile.city') AS city
FROM pgdoc.collection('{database}', 'users')
LIMIT 10;

The result is text, so numeric work needs an explicit cast:

SELECT avg((pgdoc_core.bson_get_value_text(document, 'age'))::numeric) AS avg_age
FROM pgdoc.collection('{database}', 'users');

Filter and group​

SELECT pgdoc_core.bson_get_value_text(document, 'profile.city') AS city,
count(*) AS cnt
FROM pgdoc.collection('{database}', 'users')
WHERE (pgdoc_core.bson_get_value_text(document, 'age'))::int >= 28
GROUP BY 1
ORDER BY cnt DESC;

Join with relational tables​

Collections can be joined directly with ordinary tables, which is the typical scenario for combining the two data models.

-- Assumes a relational table city_meta(city text, region text)
SELECT pgdoc_core.bson_get_value_text(u.document, 'profile.city') AS city,
m.region,
count(*) AS cnt
FROM pgdoc.collection('{database}', 'users') u
JOIN public.city_meta m
ON m.city = pgdoc_core.bson_get_value_text(u.document, 'profile.city')
GROUP BY 1, 2
ORDER BY cnt DESC;

Two document collections can be joined the same way: extract the join key on each side with bson_get_value_text() and compare.

Window functions​

-- Top 3 oldest users per city
SELECT * FROM (
SELECT pgdoc_core.bson_get_value_text(document, 'name') AS name,
pgdoc_core.bson_get_value_text(document, 'profile.city') AS city,
(pgdoc_core.bson_get_value_text(document, 'age'))::int AS age,
row_number() OVER (
PARTITION BY pgdoc_core.bson_get_value_text(document, 'profile.city')
ORDER BY (pgdoc_core.bson_get_value_text(document, 'age'))::int DESC
) AS rn
FROM pgdoc.collection('{database}', 'users')
) t
WHERE rn <= 3;

Performance characteristics​

pgdoc.collection() runs as Custom Scan (DocumentDBApiExplainQueryScan). Main characteristics:

  • Collection scope is indexed: the query only touches physical rows of the target collection, never other collections
  • Document field filters are not indexed: conditions in WHERE are evaluated row by row, so cost grows linearly with document count
  • LIMIT can stop early: scanning stops once enough rows are produced
  • count(*) does not parse document content, so it is clearly faster than queries that extract fields

Reference timings for 100,000 documents (excluding network round trips): count(*) about 5.5 ms, LIMIT 10 about 0.08 ms, field filtering about 12.5 ms, GROUP BY on a field about 20.2 ms. Results vary with data volume and instance specs.

⚠️ Note: pgdoc.collection() scans the whole collection. For high-frequency point lookups and paging, use the imperative find_cursor_first_page, which can use indexes.

Read and write with the imperative API​

Imperative API parameters correspond one-to-one with document database commands, which suits scripted operations and batch processing.

Query​

SELECT pgdoc_core.bson_to_json_string(cursorpage)::text AS result
FROM pgdoc.find_cursor_first_page(
'{database}',
pgdoc_core.bson_json_to_bson('{
"find": "users",
"filter": { "city": "Shenzhen", "age": { "$gte": 28 } },
"projection": { "name": 1, "age": 1 },
"sort": { "age": -1 },
"limit": 10
}')
);

Supported filter operators:

OperatorExample
Equality{"city":"Shenzhen"}
$gt / $gte / $lt / $lte{"age":{"$gte":28}}
$ne{"city":{"$ne":"Beijing"}}
$in / $nin{"city":{"$in":["Shenzhen","Beijing"]}}
$exists{"tags":{"$exists":true}}
$regex{"name":{"$regex":"^A"}}
$and / $or{"$or":[{"age":28},{"age":41}]}
$elemMatch{"tags":{"$elemMatch":{"$eq":"vip"}}}
Array contains{"tags":"vip"}
Nested path{"profile.city":"Shenzhen"}

💡 Tip: A non-zero cursorid means another batch is available, but cursors are not kept across requests. To export a full data set, pgdoc.collection() with standard SQL is more direct than stitching pages together.

Count​

count_query has lower overhead, but it relies on internal count statistics and lags a few seconds behind writes and deletes, during which it may return stale values:

SELECT pgdoc_core.bson_to_json_string(
pgdoc.count_query('{database}',
pgdoc_core.bson_json_to_bson('{"count":"users","query":{"city":"Shenzhen"}}'))
)::text;
-- { "n" : 2, "ok" : 1.0 }

For strongly consistent exact values, use the $count aggregation stage instead:

SELECT pgdoc_core.bson_to_json_string(cursorpage)::text AS result
FROM pgdoc.aggregate_cursor_first_page(
'{database}',
pgdoc_core.bson_json_to_bson('{
"aggregate": "users",
"pipeline": [ { "$match": { "city": "Shenzhen" } }, { "$count": "total" } ],
"cursor": {}
}')
);

Aggregation and cross-collection joins​

Supported stages: $match, $group, $project, $sort, $limit, $skip, $unwind, $lookup, $facet, $count.

SELECT pgdoc_core.bson_to_json_string(cursorpage)::text AS result
FROM pgdoc.aggregate_cursor_first_page(
'{database}',
pgdoc_core.bson_json_to_bson('{
"aggregate": "orders",
"pipeline": [
{ "$lookup": { "from": "users", "localField": "userId",
"foreignField": "_id", "as": "user" } },
{ "$unwind": { "path": "$user" } },
{ "$project": { "orderNo": 1, "userName": "$user.name" } },
{ "$limit": 10 }
],
"cursor": {}
}')
);

Bulk writes​

Large writes go through procedure interfaces invoked with CALL. A single batch insert is capped at 25,000 records:

ProcedurePurpose
insert_bulkBatch insert
update_bulkBatch update
bulkwriteMixed batch operations

The last two parameters of these procedures are INOUT (result and success flag), so pass initial values when calling — NULL covers the usual case.

Inspect the query plan​

SELECT pgdoc_core.bson_to_json_string(
pgdoc.explain('{database}',
pgdoc_core.bson_to_bytea(
pgdoc_core.bson_json_to_bson('{"find":"users","filter":{"city":"Shenzhen"}}')
))
)::text;

winningPlan.stage being IXSCAN means an index was used; COLLSCAN means a full collection scan. The second parameter is bytea, so wrap it with bson_to_bytea().

💡 Tip: With a small limit, the optimizer may deliberately choose COLLSCAN to stop early. This is a normal cost choice and does not mean the index is unusable. Remove limit before judging whether an index can be used.

Function reference​

pgdoc functions are grouped by purpose below. The tables list names and purposes only; signatures and parameters follow the version installed in your instance — inspect them with \df pgdoc.* and \df pgdoc_core.*.

Collections

FunctionPurpose
create_collectionCreate a collection
create_collection_viewCreate a collection view
drop_collectionDrop a collection; irreversible
rename_collectionRename a collection
list_collections_cursor_first_pageList collections
coll_statsCollection statistics; count is approximate
coll_modModify collection-level options

Indexes

FunctionPurpose
create_indexes_backgroundCreate indexes in the background
check_build_index_statusCheck index build status
list_indexes_cursor_first_pageList indexes
drop_indexesDrop an index (procedure; use CALL)

Document reads and writes

FunctionPurpose
insert / insert_oneInsert documents
insert_bulkBatch insert (procedure)
find_cursor_first_pageQuery with a filter; returns the first batch
cursor_get_moreRead the next batch
count_queryCount; relies on statistics
distinct_queryDistinct values
update / update_bulkUpdate (update_bulk is a procedure)
find_and_modifyFind and update
deleteDelete
bulkwriteMixed batch operations (procedure)

Aggregation and analysis

FunctionPurpose
aggregate_cursor_first_pageAggregation pipeline
explainInspect the query plan
validateValidate internal collection structure
compactReclaim collection physical space

Database-level and operations

FunctionPurpose
list_databasesList document stores
db_statsDatabase-level statistics
drop_databaseDrop an entire document store; irreversible
binary_version / binary_extended_versionEngine version
kill_cursorsClose cursors
current_op_command / kill_opInspect and terminate in-flight operations

BSON helpers (pgdoc_core)

FunctionPurpose
bson_json_to_bsonJSON text to BSON; the main way to build parameters
bson_to_json_stringBSON to Extended JSON text
bson_get_value_textRead a scalar by path as text
bson_get_valueRead a sub-document by path
bson_object_keysList top-level keys
bson_to_bytea / bson_from_byteaConvert to and from bytea, needed by explain and similar

💡 Tip: pgdoc.collection() is read-only and suits analysis and export; writes, indexes, and collection management go through the functions above.

Common errors​

Error codeMeaningWhat to check
DATABASE_42P01Object does not existCheck the collection name and schema
DATABASE_42601Syntax error or multiple statementsRun one statement per request; validate the JSON
DATABASE_42703Column does not existReturn type and call style do not match; see Match the call style to the return type
DATABASE_M000POperation not allowedFor example dropping the _id_ index
DATABASE_42501Insufficient privilegeConfirm the role has document operation rights
DATABASE_25006Write in a read-only transactionCheck whether the role is read-only