postgresql - Postgres:从匿名jsonb数组元素中删除对象
问题描述
我有一个包含 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"}]'
解决方案
好的,找到了解决方案,所以我在这里分享它,(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;
推荐阅读
- pypi - 是否可以用我自己的包替换具有特定名称的现有 pip 包?
- syntax - 如何使用 Hugo 嵌套短代码?省略了原始 HTML
- java - 如何使用 redisson 并保持微服务架构紧凑
- ios - 透明导航栏 iOS 13
- sql - 如何在 CASE 语句计算中对重复行求和
- angular - 如何使用 angular-google-charts 制作圆角条
- javascript - 我需要添加什么以及将 JWT 令牌发送到浏览器标头的位置?
- php - PHP拆分和排序新数组中的数据
- python - 余弦相似度为 -1 或 1,但我需要将它们赌为 0 和 1
- selenium - 在 Selenium 中实现数组元素