简体   繁体   中英

JSONB subset of array

I have the following JSONB field on my posts table: comments .

comments looks like this:

[
{"id": 1, "text": "My comment"},
{"id": 2, "text": "My other comment"},
]

I would like to select some information about each comments.

SELECT comments->?????? FROM posts WHERE posts.id = 1;

Is there a way for me to select only the id fields of my JSON. Eg. the result of my SQL query should be:

[{"id": 1}, {"id": 2}]

Thanks!

You can use jsonb_to_recordset to split each comment into its own row. Only columns you specify will end up in the row, so you can use this to keep only the id column. Then you can aggregate the comments for one post into an array using json_agg :

select  json_agg(c)
from    posts p
cross join lateral
        jsonb_to_recordset(comments) c(id int)  -- Only keep id
where   p.id = 1

This results in:

[{"id":1},{"id":2}]

Example at db-fiddle.com

You may use json_build_object + json_agg

select json_agg(json_build_object('id',j->>'id'))
from  posts cross join jsonb_array_elements(comments) as j
where (j->>'id')::int = 1;

DEMO

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM