How to update JSON node that matches criteria based on attribute value (instead of index)?

时间:2018-08-22 13:44:26

标签: postgresql postgresql-json

Postgresql 10+

Example from the documentation...

jsonb_set('[{"f1":1,"f2":null},2,null,3]', '{0,f1}','[2,3,4]', false)

results in...

[{"f1":[2,3,4],"f2":null},2,null,3]

Fair enough. But I need to find my target node by attribute value, not index. For the life of me, I cannot figure out how do something like...

jsonb_set('[{"f1":1,"f2":null},2,null,3]', '{(where f1 = 1),f1}','[2,3,4]', false)

Any advice on how to accomplish this? Thanks!

1 个答案:

答案 0 :(得分:2)

您可以将步骤分为两个作业:

  1. 拆分为元素(jsonb_arral_elements)
  2. 确定夹心元素是否必须更改(何时……)
  3. 更新该元素(jsonb_set)
  4. 一起加入(jsonb_agg)

解决方案

select jsonb_agg(case when element->>'f1'='1' then jsonb_set(element, '{f1}', '[2,3,4]') else element end)
  from jsonb_array_elements('[{"f1":1,"f2":null},2,null,3,{"f1":3},{"f1":1,"f2":2}]'::jsonb) element

注释

我更改了输入,并使用“ f1”键添加了另外两个元素