简体   繁体   English

Jsonb_set:如何使用键更新所有数组元素

[英]Jsonb_set: How to Update ALL array elements with key

I have a table 'things' with a set of columns 我有一个带有一组列的表“物”

id | name | data
1  | 'hi' | [{name: 'what', amount: 10}, {name:'koo', amount: 15}, {name: 'boo', amount: 13}] 

I want to change the amount to 0, in all of the array elements. 我想将所有数组元素的数量更改为0。 Ie, I want the result to be 即,我希望结果是

[{name: 'what', amount: 0}, {name:'koo', amount:0}, {name: 'boo', amount: 0}]

When I do this 当我这样做时

UPDATE      things
SET         data = jsonb_set(data, '{0,amount}', '0', false)
WHERE       id=1

This works, but only sets the first array element amount to 0. Ie the result is 这有效,但仅将第一个数组元素的数量设置为0。即结果是

[{name: 'what', amount: 0}, {name:'koo', amount: 15}, {name: 'boo', amount: 13}] 

I want them all to be 0. 我希望它们全部为0。

How do I do that? 我怎么做?

You can split it apart, update it, and put it back together again: 您可以将其拆分,更新并再次放回原处:

select id, 
       name, 
       jsonb_agg(jsonb_set(array_elems, '{amount}', '0')) -- update each element of the array and aggregate them back together
FROM things
JOIN LATERAL (
    select jsonb_array_elements(data) -- split the array into each element
) sub(array_elems) ON TRUE
GROUP BY id, name;
 id | name |                                          jsonb_agg
----+------+---------------------------------------------------------------------------------------------
  1 | hi   | [{"name": "what", "amount": 0}, {"name": "koo", "amount": 0}, {"name": "boo", "amount": 0}]

Here is the step of updating the table. 这是更新表的步骤。

WITH updated_data AS (
  select id, 
       jsonb_agg(jsonb_set(array_elems, '{amount}', '0')) as updated
  FROM things
  JOIN LATERAL (
    select jsonb_array_elements(data) -- split the array into each element
  ) sub(array_elems) ON TRUE
  GROUP BY id
)
UPDATE things set data = updated
FROM updated_data 
WHERE things.id = updated_data.id;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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