Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove multiple keys from jsonb column in one statement

I'm trying to remove multiple keys from a jsonb column.

I've managed to get it to delete a single key with the following statement:

UPDATE table_a
SET data_column = data_column #- '{attr_1}'
WHERE type = 'type_a'

I understand thats a path so I can't do: #- '{attr_1,attr_2}

Based on the docs I should be able to also do - 'attr_1' but that didn't work otherwise I'd attempt to try - 'attr_1,attr2'

like image 941
Sam Esmail Avatar asked Jun 18 '18 07:06

Sam Esmail


2 Answers

Or the minus operator once (but using a text array):

SELECT '{ "a": 1, "b": 2, "c": 3 }'::jsonb - '{a,b}'::text[];
 ?column? 
----------
 {"c": 3}
(1 row)
like image 133
Gerard H. Pille Avatar answered Nov 04 '22 22:11

Gerard H. Pille


If you need to remove multiple non-nested keys you can use - operator:

SELECT '{ "a": 1, "b": 2, "c": 3 }'::jsonb - ARRAY['a', 'b'];
like image 35
Ihor Sakailiuk Avatar answered Nov 04 '22 23:11

Ihor Sakailiuk