postgresql - 如何从每个元素 json 数组 postgres 中删除字段?

标签 postgresql jsonb

我有 table

    CREATE TABLE items (
    id BIGINT PRIMARY KEY ,
    data jsonb
);

数据格式

[
    {
        "id": "d20fe90c-137c-4713-bde1-2d4e75178ad3",
        "text": "text",
        "count": 1
    },
    {
        "id": "d20fe90c-137c-4713-bde1-2d4e75178ad4",
        ""text": "text",
        "count": 1
    }
]

如何从数据 json 数组的所有元素中删除字段 count

我试试

UPDATE items
SET data = data #- '{count}';

但是这个查询需要count之前数组元素的索引为

UPDATE items
    SET data = data #- '{0, count}';

最佳答案

没有运算符或内置函数可以做到这一点。取消数组嵌套并聚合修改后的元素,如下所示:

update items t
set data = (
    select jsonb_agg(elem- 'count')
    from items
    cross join lateral jsonb_array_elements(data) as arr(elem)
    where id = t.id)

db<>fiddle.中进行测试

关于postgresql - 如何从每个元素 json 数组 postgres 中删除字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69481613/

相关文章:

json - PostgreSQL引入JSONB的解释

postgresql - 为 PostgreSQL 表创建别名

SQL查询只获取在特定列中包含给定值的记录

postgresql - PostgreSQL 中固定大小 JSONB 数组的聚合

sql - 避免在 CASE 语句中进行 PostgreSQL 类型评估

arrays - 使用 Postgres JSONB 查询查询数组中的数组

java - 如何使用 Spring Data JPA 查询更新 PostgreSQL 中的 JSONB 列

ruby-on-rails - 数据库迁移脚本中断引用

ruby-on-rails - Rails 默认为定义的值

postgresql - postgres 无法统计文件 <basexxxx/xxxx> 权限被拒绝