How to update the JSONB to add new key into nested array (for all items of array) for all the records.
I'm referring to the link The table structure is:
CREATE TABLE orders (
id serial PRIMARY KEY,
data jsonb
);
The given json is:
{
"Number": "555",
"UserId": "1",
"Items": [
{
"ProductId": "1",
"Name": "TV",
"Price": "300.00"
},
{
"ProductId": "2",
"Name": "Mechanical Keyboard",
"Price": "120.00"
}
]
}
To add new element into each array item the following query is given:
UPDATE orders
SET data = jsonb_set(
data,
'{Items}', -- the array in which we operate
to_jsonb(
(WITH ar AS(
WITH temp AS(
SELECT data->'Items' AS items -- the array in which we operate
FROM orders
WHERE id = 1 -- the filtered order we are updating
)
SELECT jsonb_set(
jsonb_array_elements(items),
'{Quantity}', -- the new field we are adding
'"1"', -- the value of the new field
true)
FROM temp)
SELECT (array_agg(ar.jsonb_set))
FROM ar)),
false)
WHERE id = 1;
Output after executing above query:
{
"Number": "555",
"UserId": "1",
"Items": [
{
"ProductId": "1",
"Name": "TV",
"Price": "300.00",
"Quantity": "1"
},
{
"ProductId": "2",
"Name": "Mechanical Keyboard",
"Price": "120.00",
"Quantity": "1"
}
]
}
But above will update the json only where id=1
. What changes are required to update JSON same as above for all rows in orders ?
WITH
clause to convert the JSON into a table, and useUPDATE ... FROM
to perform a join with that table. – Laurenz Albejsonb_populate_recordset
or similar to builld a table. – Laurenz Albe