postgres jsonb_set 多键更新

postgres jsonb_set multiple keys update

我有带 jsonb 列的数据库 table。

number  | data
    1   | {"name": "firstName", "city": "toronto", "province": "ON"}

我需要一种更新数据列的方法。 所以我的输出应该是这样的:

{"name": "firstName", "city": "ottawa", "province": "ON", "phone": "phonenum", "prefix": "prefixedName"}

json_set可以吗? 我添加了如下查询:

update table_name set data = jsonb_set(data, '{city}', '"ottawa"') where number = 1;

但是,我需要一种方法来添加新的键值(如果不存在)并更新键值(如果存在)。是否可以在单个查询中实现?

documentation says:

The || operator concatenates the elements at the top level of each of its operands. ... For example, if both operands are objects with a common key field name, the value of the field in the result will just be the value from the right hand operand.

因此使用您的示例数据:

update table_name set
    data = data || '{"city": "ottawa", "phone": "phonenum", "prefix": "prefixedName"}'
    where number = 1;

此外,如果您要编辑的对象不在顶层 - 只需结合连接和 jsonb_set 功能。例如,如果原始数据看起来像

{"location": {"name": "firstName", "city": "toronto", "province": "ON"}}

然后

...
data = jsonb_set(
    data, 
    '{location}', data->'location' || '{"city": "ottawa", "phone": "phonenum", "prefix": "prefixedName"}')
...

你可以试试这个

这里我们使用jsonb连接运算符||连接两个json对象

update table_name set data = (select val from (
(select 
CASE WHEN data ? key THEN jsonb_set(data, '{' || key || '}', quote_nullable(updated_value))
ELSE 
data || ('{' || quote_ident(key) || ':' || quote_ident(some_value) || '}')::jsonb
END val
 from json_each_text((select data::json from tbl))
CROSS JOIN tbl t
where key in ('city','phone','prefix') and number=1)) where number=1