在我的表中,我有一个jsonb类型的列。 示例jsonb数据:
{
"id": "1",
"customer":[{"id": "1", "isPosted": "false"},{"id": "2","isPosted": "false"}]
}
是否可以将名为isPosted的所有元素更新为“true”?
答案 0 :(得分:0)
你可以在这里使用猴子黑客 - 替换值并将结果用作jsonb:
t=# with c(j) as (values('{"id": "1", "customer":[{"id": "1", "isPosted": "false"},{"id": "2","isPosted": "false"}]} '::jsonb))
select *,replace(j::text,'"isPosted": "false"','"isPosted": "true"')::jsonb from c;
-[ RECORD 1 ]------------------------------------------------------------------------------------------
j | {"id": "1", "customer": [{"id": "1", "isPosted": "false"}, {"id": "2", "isPosted": "false"}]}
replace | {"id": "1", "customer": [{"id": "1", "isPosted": "true"}, {"id": "2", "isPosted": "true"}]}
t=# with c(j) as (values('{"id": "1", "customer":[{"id": "1", "isPosted": "false"},{"id": "2","isPosted": "false"}]} '::jsonb))
, n as (select jsonb_set(e,'{isPosted}'::text[],'true'),j from c, jsonb_array_elements(j->'customer') with ordinality a (e,o))
select jsonb_set(j,'{customer}'::text[],jsonb_agg(jsonb_set)) from n group by j;
jsonb_set
-----------------------------------------------------------------------------------------
{"id": "1", "customer": [{"id": "1", "isPosted": true}, {"id": "2", "isPosted": true}]}
(1 row)