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
pgdocis enabled; see Enable pgdoc- Use the SQL Editor provided by the CloudBase console to run the SQL in this page; open it at Console → Database → SQL Editor
- For a graphical connection instead, use DMC database management or psql; see Connecting to PostgreSQL
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 point | Typical functions | Characteristics |
|---|---|---|
| Imperative API | pgdoc.find_cursor_first_page, pgdoc.aggregate_cursor_first_page | Parameters match document database commands; supports indexes, cursors, and aggregation pipelines; reads and writes |
| Collection function | pgdoc.collection | Treats a collection as a table for standard SQL filtering, grouping, and joins; read-only |
Both read the same data. Choose by scenario:
| Scenario | Recommended entry point |
|---|---|
Exact lookup by _id or an indexed field, paged traversal | Imperative API |
| Inserts, updates, deletes | Imperative API |
| Joins with relational tables, UNION across collections, window functions | pgdoc.collection |
| Data export, offline analysis | pgdoc.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 type | Typical functions | Call style |
|---|---|---|
record | insert, update, delete, find_cursor_first_page | SELECT column FROM pgdoc.xxx(...) |
bson | count_query, distinct_query, coll_stats | SELECT pgdoc_core.bson_to_json_string(pgdoc.xxx(...))::text |
boolean / void | create_collection, drop_collection, rename_collection | SELECT pgdoc.xxx(...) |
procedure | insert_bulk, drop_indexes | CALL 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;
| Column | Type | Description |
|---|---|---|
shard_key_value | bigint | Internal collection identifier; usually not of interest |
object_id | bson | The document _id, stored as single-key BSON |
document | bson | Full 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
WHEREare evaluated row by row, so cost grows linearly with document count LIMITcan stop early: scanning stops once enough rows are producedcount(*)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 imperativefind_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:
| Operator | Example |
|---|---|
| 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
cursoridmeans 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:
| Procedure | Purpose |
|---|---|
insert_bulk | Batch insert |
update_bulk | Batch update |
bulkwrite | Mixed 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 chooseCOLLSCANto stop early. This is a normal cost choice and does not mean the index is unusable. Removelimitbefore 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
| Function | Purpose |
|---|---|
create_collection | Create a collection |
create_collection_view | Create a collection view |
drop_collection | Drop a collection; irreversible |
rename_collection | Rename a collection |
list_collections_cursor_first_page | List collections |
coll_stats | Collection statistics; count is approximate |
coll_mod | Modify collection-level options |
Indexes
| Function | Purpose |
|---|---|
create_indexes_background | Create indexes in the background |
check_build_index_status | Check index build status |
list_indexes_cursor_first_page | List indexes |
drop_indexes | Drop an index (procedure; use CALL) |
Document reads and writes
| Function | Purpose |
|---|---|
insert / insert_one | Insert documents |
insert_bulk | Batch insert (procedure) |
find_cursor_first_page | Query with a filter; returns the first batch |
cursor_get_more | Read the next batch |
count_query | Count; relies on statistics |
distinct_query | Distinct values |
update / update_bulk | Update (update_bulk is a procedure) |
find_and_modify | Find and update |
delete | Delete |
bulkwrite | Mixed batch operations (procedure) |
Aggregation and analysis
| Function | Purpose |
|---|---|
aggregate_cursor_first_page | Aggregation pipeline |
explain | Inspect the query plan |
validate | Validate internal collection structure |
compact | Reclaim collection physical space |
Database-level and operations
| Function | Purpose |
|---|---|
list_databases | List document stores |
db_stats | Database-level statistics |
drop_database | Drop an entire document store; irreversible |
binary_version / binary_extended_version | Engine version |
kill_cursors | Close cursors |
current_op_command / kill_op | Inspect and terminate in-flight operations |
BSON helpers (pgdoc_core)
| Function | Purpose |
|---|---|
bson_json_to_bson | JSON text to BSON; the main way to build parameters |
bson_to_json_string | BSON to Extended JSON text |
bson_get_value_text | Read a scalar by path as text |
bson_get_value | Read a sub-document by path |
bson_object_keys | List top-level keys |
bson_to_bytea / bson_from_bytea | Convert 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 code | Meaning | What to check |
|---|---|---|
DATABASE_42P01 | Object does not exist | Check the collection name and schema |
DATABASE_42601 | Syntax error or multiple statements | Run one statement per request; validate the JSON |
DATABASE_42703 | Column does not exist | Return type and call style do not match; see Match the call style to the return type |
DATABASE_M000P | Operation not allowed | For example dropping the _id_ index |
DATABASE_42501 | Insufficient privilege | Confirm the role has document operation rights |
DATABASE_25006 | Write in a read-only transaction | Check whether the role is read-only |