PostgreSQL:通过函数将对象添加到jsonb数组
PostgreSQL: Add object to jsonb array by function
我有这个 jsonb
数组:
[{"id": 1, "foo": false}, {"id": 1, "foo": true}]
我一直在努力尝试为里面的所有对象添加另一个字段。这是我正在寻找的结果:
[{"id": 1, "foo": false, "bar": true}, {"id": 1, "foo": true, "bar": true}]
我知道我需要编写一个函数,但我是 PostgreSQL 的新手,所以我不确定从哪里开始。这是我能找到的最接近的线程: 但他们要通过密钥更新现有对象。
非常感谢任何帮助或指出方向。
编辑:
我试过改成这个功能
create or replace function add_elements(arr jsonb)
returns jsonb language sql as $$
select jsonb_agg(jsonb_build_object("bar", true))
from jsonb_array_elements(arr) e(e)
$$;
但是 PostgreSQL 抱怨 ERROR: column "bar" does not exist
我正在使用 Postgres 9.5
对来自 jsonb_array_elements()
:
的元素使用连接运算符
with my_table(arr) as (
values
('[{"id": 1, "foo": false}, {"id": 1, "foo": true}]'::jsonb)
)
select jsonb_agg(elem || '{"bar": true}'::jsonb)
from my_table,
jsonb_array_elements(arr) elem;
jsonb_agg
-----------------------------------------------------------------------------
[{"id": 1, "bar": true, "foo": false}, {"id": 1, "bar": true, "foo": true}]
(1 row)
您的函数可能如下所示:
create or replace function add_elements(arr jsonb, val jsonb)
returns jsonb language sql as $$
select jsonb_agg(elem || val)
from jsonb_array_elements(arr) elem
$$;
with my_table(arr) as (
values
('[{"id": 1, "foo": false}, {"id": 1, "foo": true}]'::jsonb)
)
select add_elements(arr, '{"bar": true}')
from my_table;
add_elements
-----------------------------------------------------------------------------
[{"id": 1, "bar": true, "foo": false}, {"id": 1, "bar": true, "foo": true}]
(1 row)
我有这个 jsonb
数组:
[{"id": 1, "foo": false}, {"id": 1, "foo": true}]
我一直在努力尝试为里面的所有对象添加另一个字段。这是我正在寻找的结果:
[{"id": 1, "foo": false, "bar": true}, {"id": 1, "foo": true, "bar": true}]
我知道我需要编写一个函数,但我是 PostgreSQL 的新手,所以我不确定从哪里开始。这是我能找到的最接近的线程:
非常感谢任何帮助或指出方向。
编辑:
我试过改成这个功能
create or replace function add_elements(arr jsonb)
returns jsonb language sql as $$
select jsonb_agg(jsonb_build_object("bar", true))
from jsonb_array_elements(arr) e(e)
$$;
但是 PostgreSQL 抱怨 ERROR: column "bar" does not exist
我正在使用 Postgres 9.5
对来自 jsonb_array_elements()
:
with my_table(arr) as (
values
('[{"id": 1, "foo": false}, {"id": 1, "foo": true}]'::jsonb)
)
select jsonb_agg(elem || '{"bar": true}'::jsonb)
from my_table,
jsonb_array_elements(arr) elem;
jsonb_agg
-----------------------------------------------------------------------------
[{"id": 1, "bar": true, "foo": false}, {"id": 1, "bar": true, "foo": true}]
(1 row)
您的函数可能如下所示:
create or replace function add_elements(arr jsonb, val jsonb)
returns jsonb language sql as $$
select jsonb_agg(elem || val)
from jsonb_array_elements(arr) elem
$$;
with my_table(arr) as (
values
('[{"id": 1, "foo": false}, {"id": 1, "foo": true}]'::jsonb)
)
select add_elements(arr, '{"bar": true}')
from my_table;
add_elements
-----------------------------------------------------------------------------
[{"id": 1, "bar": true, "foo": false}, {"id": 1, "bar": true, "foo": true}]
(1 row)