将jsonb键值转换为键值数组

Convert jsonb key value to key value array

对于笔记应用程序,我的 PostgreSQL 模式中现在有以下 json 文档:

postgres=# select id, data from notes where id=107;
 id  |                                           data                                           
-----+-----------------------------------------------------------------    
 107 | {"tag": "sample tag", "title": "sample title", "content": "sample title\n\nsample text"}

为了将来能够使用多个标签,我想将我数据库中的每个现有条目从上面转换为这样的数组:"tag": ["sample tag"]

我做了一些研究,通过四处游玩,我得到了一些类似的东西:

UPDATE notes SET data = jsonb_set(data, '{tag}', $$["sample tag", "xyz"]$$);

这实际上将行从 "tag": "sample tag" 更新为 "tag": ["sample tag", "xyz"],但我希望它通过我所有带有现有标签的条目动态地 运行。我想不出一种方法来 运行 类似于 jsonb_set 部分中的子查询。

使用函数jsonb_build_array():

update notes
set data = jsonb_set(data, '{tag}', jsonb_build_array(data->'tag'));

Working example in rextester.