jsonb_array_elements_text Unnests JSON Arrays

Expand a JSONB array back into rows with jsonb_array_elements_text, keep each element's position with WITH ORDINALITY, then re-aggregate with jsonb_agg.

SqlData Fetching

Code

snippet
-- JSONB 数组还原成行:每个元素一行,WITH ORDINALITY 保留原始位次
SELECT
    doc_id,
    tag,
    ord - 1 AS tag_index          -- ordinality 从 1 起,转成 0 基下标
FROM docs,
     LATERAL jsonb_array_elements_text(doc->'tags') WITH ORDINALITY AS t(tag, ord)
ORDER BY doc_id, ord;

-- 反向聚合:jsonb_agg 把行重新收成 JSONB 数组
SELECT
    doc_id,
    jsonb_agg(tag ORDER BY ord) AS tags_restored
FROM docs,
     LATERAL jsonb_array_elements_text(doc->'tags') WITH ORDINALITY AS t(tag, ord)
GROUP BY doc_id;

-- 展开后就能按元素筛选:找带某标签的文档
SELECT doc_id FROM docs, LATERAL jsonb_array_elements_text(doc->'tags') AS t(tag)
WHERE tag = 'urgent';

How it works

SELECT statements share the script, touching docs.

Breaking the statements into their working parts: a WHERE clause constraining which rows the statement operates on; a GROUP BY that collapses matching rows into one output row per group; an ORDER BY that fixes the output order.

Applying it

Run the statement against the docs table.

Statements that matter

SELECT
    doc_id,
    jsonb_agg(tag ORDER BY ord) AS tags_restored
FROM docs,
     LATERAL jsonb_array_elements_text(doc->'tags') WITH ORDINALITY AS t(tag, ord)
GROUP BY doc_id;
SELECT
    doc_id,
    tag,
    ord - 1 AS tag_index          -- ordinality 从 1 起,转成 0 基下标
FROM docs,
     LATERAL jsonb_array_elements_text(doc->'tags') WITH ORDINALITY AS t(tag, ord)
ORDER BY doc_id, ord;
SELECT doc_id FROM docs, LATERAL jsonb_array_elements_text(doc->'tags') AS t(tag)
WHERE tag = 'urgent';

Interactive Tools for This Topic

FAQ

What are the relations in play here?
`docs`.