更新包含数组的jsonb列中的选定值

时间:2019-01-08 12:27:18

标签: postgresql sql-update jsonb

faults包含列recacc(jsonb),其中包含json对象数组。它们每个都包含一个字段action。如果action的值为abc,我想将其更改为cba。更改将应用​​于所有行。

[
  {
    "action": "abc",
    "created": 1128154425441
  },
  {
    "action": "lmn",
    "created": 1228154425441
  },
  {
    "action": "xyz",
    "created": 1328154425441
  }
]

以下操作无效,可能是因为数据为数组格式

update faults 
  set recacc = jsonb_set(recacc,'{action}', to_jsonb('cbe'::TEXT),false) 
where recacc ->> 'action' = 'abc'

1 个答案:

答案 0 :(得分:0)

我不确定这是否是最好的选择,但是您可能首先使用jsonb_array_elements获取jsonb的元素,将其替换,然后使用array_aggarray_to_json来重建json

UPDATE faults SET recacc = new_recacc::jsonb
FROM 
 (SELECT array_to_json(array_agg(s)) as new_recacc 
 FROM
   (  SELECT 
         replace(c->>'action','abc','cba') , --this to change the value
          c->>'created' FROM faults f
       cross join lateral jsonb_array_elements(f.recacc)  as c
   )  as s (action,created)
) m;

Demo