PostgreSQL:使用json对象从数组中删除键/值对

编程入门 行业动态 更新时间:2024-10-25 10:22:12
本文介绍了PostgreSQL:使用json对象从数组中删除键/值对的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一张桌子:

CREATE TABLE movies( id text, data jsonb ); INSERT INTO movies(id, data) VALUES ( '1', { "actors": [ { "name": "actor1", "email": "actor1@somemail" }, { "name": "actor2", "email": "actor2@somemail" } ] } );

我想要从actor数组的每个json对象中删除电子邮件字段(键+值).

What I want is to delete the email field (key + value) from each json object of the actors array.

我尝试了以下解决方案,尽管它确实执行了,但它对数组完全没有任何作用:

I've tried the following solution and although it does execute, it doesn't have any effect on the array at all:

update movies set data = jsonb_set(data, '{actors}', (data->'actors') - '{actors, email}') where id = '1';

推荐答案

要操作数组中的所有项,您将需要使用子查询:

To manipulate all items in the array, you will need to use a subquery:

UPDATE movies SET data = jsonb_set(data, '{actors}', ( SELECT jsonb_agg(actor - 'email') FROM jsonb_array_elements(data->'actors') actor )) WHERE id = '1';

((在线演示)

更多推荐

PostgreSQL:使用json对象从数组中删除键/值对

本文发布于:2023-10-19 18:10:54,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1508346.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:组中   对象   PostgreSQL   json

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!