Postgresql update a value in a jsonb array column

这一生的挚爱 提交于 2021-02-11 14:45:11

问题


I have one table with a jsonb and this data inside:

[
{
    "valor": "2025,79",
    "parcela": 46,
    "vencimento": 1570503600000
},
{
    "valor": "1987,7",
    "parcela": 47,
    "vencimento": 1573182000000
},
{
    "valor": "1950,47",
    "parcela": 48,
    "vencimento": 1575774000000
},
{
    "valor": "1912,88",
    "parcela": 49,
    "vencimento": 1578452400000
}

]

but now I need in all row, alter the value in "vencimento" from 1573182000000 to "10/10/2010"

it's possible ?

with this code I can split the array in columns and change te value

SELECT id, jsonb_set(d, '{vencimento}',
 quote_ident(to_char(to_timestamp(cast((d -> 'vencimento')::varchar as bigint) / 1000)::date, 'dd/mm/yyyy'))::jsonb
) 
    FROM notificato.requerimento, jsonb_array_elements(parcela) d where id = 1;

but how can I update my row?

tks


回答1:


Collect the values back to a jsonb array with jsonb_agg and assign that to your column:

UPDATE notificato.requerimento
SET parcela = (SELECT jsonb_agg(
  jsonb_set(d, '{vencimento}', to_jsonb(to_char(to_timestamp((d ->> 'vencimento')::bigint / 1000)::date, 'dd/mm/yyyy'))
) FROM jsonb_array_elements(parcela) d)
WHERE id = 1;


来源:https://stackoverflow.com/questions/60325238/postgresql-update-a-value-in-a-jsonb-array-column

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!