Find position of object in postgres jsonb array

大城市里の小女人 提交于 2019-12-08 05:12:30

Example data:

create temp table settings as
select 
    '{"west": [
      {"id": "aa92f346-7a93-4443-949b-4eab0badd983", "version": 1},
      {"id": "cd92e346-6b04-3456-050a-5eeb0bddd027", "version": 3}
    ]}'::jsonb as value;

You can use jsonb_array_elements() with ordinality to determine the array position of a given element:

select elem, position
from settings, jsonb_array_elements(value->'west') with ordinality arr(elem, position)
where elem->>'id' = 'cd92e346-6b04-3456-050a-5eeb0bddd027';

                             elem                             | position 
--------------------------------------------------------------+----------
 {"id": "cd92e346-6b04-3456-050a-5eeb0bddd027", "version": 3} |        2
(1 row)

Use position to remove the object from the array:

select value #- array['west', (position- 1)::text] new_value
from settings, jsonb_array_elements(value->'west') with ordinality arr(elem, position)
where elem->>'id' = 'cd92e346-6b04-3456-050a-5eeb0bddd027';

                                new_value                                 
--------------------------------------------------------------------------
 {"west": [{"id": "aa92f346-7a93-4443-949b-4eab0badd983", "version": 1}]}
(1 row)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!