I need to update a jsonb object in PostgreSQL but am unable to identify the correct syntax for updating the same, below are the use cases for the same.
Data in table
Create table jsondata (id int, data jsonb);
INSERT INTO jsondata VALUES
(1,'[{"cc": null, "subsectionid": 26}, {"cc": null, "subsectionid": 27}]');
SELECT * from jsondata;
Use case:
Want to update the value of cc where subsectionid =27
Query tried:
UPDATE jsondata
SET data = data || '{null: ["Lake Providence"]}'::jsonb
WHERE data->>'subsectionid' = '27'
Please help me to achieve this.
4
Answers
I hope somebody comes along with a simpler answer, but this shows how I would break down the jsonb and then build it back up for the update:
Fiddle
Since your top-level
jsonb
entity is an array, you can filter out the element you want to update, or rather pick everything but that in ajsonb_path_query_array()
, then add the replacement.@?
operator (orjsonb_path_exists()
) let you pinpoint your targets with wildcards in jsonpath: demoUse
jsonb_array_elements
on the data, add the property to the object(s) where you want, thenjsonb_agg
regate them back to an array.json_set function.
main idea from:
select jsonb_set('[{"cc": null, "subsectionid": 26}, {"cc": null, "subsectionid": 27}]', '{1,cc}', '"Lake Providence"', false);