Postgres:从匿名jsonb数组元素中删除对象

问题描述 投票:0回答:1

我有一个包含2个字段的表:

table documents
  docu_id     uuid
  attachments jsonb

attachments jsonb列的示例数据将是:

[
 {
    "size": 10,
    "attach_id": "d3a21f904068"
 },{
    "Size": 0.143,
    "attach_id": "5ba4b285565b"
 }
]

我已经看到很多关于如何根据字段名更新/删除jsonb的例子,但是有可能从匿名数组中删除一个匿名对象,其中"attach_id" = "X" and "docu_id"="Y":

delete from documents
  where docu_id = "Y" 
    and
    where attachments @> '[{"attach_id": "X"}]'
postgresql postgresql-9.3 postgresql-9.4
1个回答
0
投票

好的找到了解决方案,所以我在这里分享,(rextester link http://rextester.com/YICZ86369):

Inserting the data

  create table documents(docu_id text, attachments jsonb);
    insert into documents values
    ('001', 
    '[
      {
        "name": "uno",
        "id":"1"
      },
       {
        "name": "dos",
        "id":"2"
      },
       {
        "name": "tres",
        "id":"3"
      }
    ]'
    ),
    ('002', 
    '[
      {
        "name": "eins",
        "id":"1"
      },
       {
        "name": "zwei",
        "id":"2"
      }
    ]'
    );
    select * from documents;

enter image description here

The solution

UPDATE documents
   SET attachments = attachments #- 
          array(
                    SELECT i
                      FROM generate_series(0, jsonb_array_length(attachments) - 1) AS i
                      WHERE (attachments->i->'id' = '"2"')
           )::text[] /* cast as text */
       where docu_id = '002';

select * from documents;

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.