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

孤街醉人 提交于 2021-01-28 02:07:04

问题


I have a table:

CREATE TABLE movies( id text, data jsonb );

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

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';

回答1:


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)




回答2:


You need to specify indexes individually to delete the array element email

update movies
   set data = jsonb_set(data, '{actors}', data -> 'actors' #- '{0,email}' #- '{1,email}')
 where id = '1';

the path element {1,email} might be replaced by {-1,email} (Negative integers count from the end).

Demo



来源:https://stackoverflow.com/questions/58882660/postgresql-delete-key-value-pair-from-array-with-json-objects

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