如何通过键值删除元素形式postgres jsonb?

时间:2017-07-09 16:26:25

标签: postgresql jsonb postgresql-9.6

我有一个这种格式的jsonb列。

{
    "categoryList": [{
        "category_menu_id": "51",
        "is_featured_product": 0
    }, {
        "category_menu_id": "54",
        "is_featured_product": 1
    }]
}

如何按category_menu_id删除类别?

此选择查询通过category_menu_id正常工作。

select product_category 
from product  
where product_category->'categoryList' @> '[{"category_menu_id": "51"}]';

1 个答案:

答案 0 :(得分:3)

示例数据(请注意我添加了主键id以启用更新表):

create table product(id int primary key, product_category jsonb);
insert into product values
(1, 
'{
    "categoryList": [{
        "category_menu_id": "51",
        "is_featured_product": 0
    }, {
        "category_menu_id": "54",
        "is_featured_product": 1
    }]
}');

此查询从json数组中跳过"category_menu_id": "51"的元素:

select jsonb_build_object('categoryList', jsonb_agg(value))
from product,
jsonb_array_elements(product_category->'categoryList')
where value->>'category_menu_id' <> '51';

                            jsonb_build_object                            
--------------------------------------------------------------------------
 {"categoryList": [{"category_menu_id": "54", "is_featured_product": 1}]}
(1 row) 

使用以上查询更新表格:

update product p
set product_category = (
    select jsonb_build_object('categoryList', jsonb_agg(value))
    from product ps,
    jsonb_array_elements(product_category->'categoryList')
    where ps.id = p.id      -- important! primary key to identify a row
    and value->>'category_menu_id' <> '51')
returning *;

 id |                             product_category                             
----+--------------------------------------------------------------------------
  1 | {"categoryList": [{"category_menu_id": "54", "is_featured_product": 1}]}
(1 row)