Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PostgreSQL: Delete key/value pair from array with json objects

I have a table:

CREATE TABLE movies( id text, data jsonb );

INSERT INTO movies(id, data) VALUES (
  '1', 
  {
      "actors": [
        {
            "name": "actor1",
            "email": "[email protected]"
        },
        {
            "name": "actor2",
            "email": "[email protected]"
        }
      ]
  }
);

What I want is to delete the email field (key + value) from each json object of the actors array.

I've tried the following solution and although it does execute, it doesn't have any effect on the array at all:

update movies
set data = jsonb_set(data, '{actors}', (data->'actors') - '{actors, email}')
where id = '1';
like image 805
Eltjon Sulaj Avatar asked Oct 22 '25 16:10

Eltjon Sulaj


1 Answers

To manipulate all items in the array, you will need to use a subquery:

UPDATE movies
SET data = jsonb_set(data, '{actors}', (
  SELECT jsonb_agg(actor - 'email')
  FROM jsonb_array_elements(data->'actors') actor
))
WHERE id = '1';

(online demo)

like image 132
Bergi Avatar answered Oct 25 '25 11:10

Bergi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!