【问题标题】:Postgres: Delete object from anonymous jsonb array elementPostgres:从匿名jsonb数组元素中删除对象
【发布时间】:2018-08-29 18:20:21
【问题描述】:

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

table documents
  docu_id     uuid
  attachments jsonb

attachments jsonb 列的示例数据为:

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

我已经看到很多关于如何根据字段名称更新/删除 jsonb 的示例,但是是否可以从 匿名数组 中删除 匿名对象 其中@ 987654324@

delete from documents
  where docu_id = "Y" 
    and
    where attachments @> '[{"attach_id": "X"}]'

【问题讨论】:

  • 您想从表格中删除整个行吗?还是只是数组中的一个元素?
  • @a_horse_with_no_name 只是数组中的元素。从附件 jsonb 数组中删除 attach_id = "X"

标签: postgresql postgresql-9.3 postgresql-9.4


【解决方案1】:

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

插入数据

  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;

解决办法

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;

【讨论】:

    猜你喜欢
    • 2015-07-12
    • 1970-01-01
    • 1970-01-01
    • 2019-09-03
    • 1970-01-01
    • 2021-02-28
    • 1970-01-01
    • 2021-01-08
    • 2022-05-25
    相关资源
    最近更新 更多