首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >更新对象的动态jsonb数组

更新对象的动态jsonb数组
EN

Database Administration用户
提问于 2020-06-15 07:50:11
回答 1查看 508关注 0票数 1

我正在尝试用一个新值更新一个jsonb键,但是我不能一次更新所有的键。

我的json结构是这样的:

代码语言:javascript
复制
[{
    "type": "button",
    "content": {
        "align": "leftAlign"
    }
}, {
    "type": "button",
    "content": {
        "align": "leftAlign"
    }
}, {
    "type": "button",
    "content": {
        "align": "leftAlign"

    }
}] 

我想用一个新值更新align键,但是现在我的查询没有更新所有的元素,它只更新一个元素。

到目前为止,这是我的疑问:

代码语言:javascript
复制
with align_position as (
    select 
    ('{' || index-1 || ',content,align}' )::text[] as path,
    id
    from section, jsonb_array_elements(entities) with ordinality arr(entity, index)
    where entity->'content'->>'align' = 'leftAlign'
)
update myTable set entities = jsonb_set(entities, align_position.path, '"left"', false) from align_position where section.id = align_position.id;

如何使查询更新所有元素?

有什么想法吗?

EN

回答 1

Database Administration用户

回答已采纳

发布于 2020-06-18 07:22:58

我设法使用以下查询解决了这个问题:

代码语言:javascript
复制
update
   myTable 
set
   entities = 
   (
      select
         to_jsonb(array_agg (new_values)) 
      from
         (
            select
(
               case
                  when
                     arr -> 'content' ->> 'align' = 'leftAlign' 
                  then
                     jsonb( COALESCE( jsonb_set(arr, '{content}', jsonb(arr ->> 'content') - 'align' || jsonb('{"align": "left"}'), true), '{}' ) ) 
                  when
                     arr -> 'content' ->> 'align' = 'rightAlign' 
                  then
                     jsonb( COALESCE( jsonb_set(arr, '{content}', jsonb(arr ->> 'content') - 'align' || jsonb('{"align": "right"}'), true), '{}' ) ) 
                  when
                     arr -> 'content' ->> 'align' = 'centerAlign' 
                  then
                     jsonb( COALESCE( jsonb_set(arr, '{content}', jsonb(arr ->> 'content') - 'align' || jsonb('{"align": "center"}'), true), '{}' ) ) 
                  else
                     arr 
               end
) as new_values 
            from
               jsonb_array_elements( entities ) as arr 
               group by
                  arr -> 'content' ->> 'align',
                  arr 
         )
         as new_values 
   )
;
票数 0
EN
页面原文内容由Database Administration提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://dba.stackexchange.com/questions/269169

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档