postgres jsonb_set多键更新 [英] postgres jsonb_set multiple keys update

查看:855
本文介绍了postgres jsonb_set多键更新的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有带有jsonb列的数据库表。

I have DB table with jsonb column.

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

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

I need a way to update data column. So my output should look like:

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

json_set是否可能?
我添加了以下查询:

Is it possible with json_set? I have added query like:

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

但是,我需要一种方法来添加不存在的新键值并更新键值如果存在。

However, I need a way to add new key-value if it does not exists and update key value if it exists. Is it possible to achieve this in single query?

推荐答案

文档中的内容


|运算符将元素串联在每个操作数的顶级。 ... 例如,如果两个操作数都是具有相同键字段名称的对象,则结果中字段的值将只是右侧操作数的值。

因此,使用您的示例数据:

So using your example data:

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

此外,如果您要编辑的对象不在顶层,只需将串联和 jsonb_set 函数。例如,如果原始数据看起来像

Additionally if the object you want to edit is not at the top level - just combine the concatenation and jsonb_set function. For example, if the original data looks like

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

然后

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

这篇关于postgres jsonb_set多键更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆