更新时如何在postgresql jsonb字段中附加对象

How to append object in postgresql jsonb field while update

我想更新我的 jsonb 字段,它存储对象数组。 我想在其中添加新对象。

CREATE TABLE justjson ( id INTEGER, doc JSONB);
INSERT INTO justjson VALUES ( 1, '[
  {
    "name": "abc",
    "age": "22"
  },
  {
    "name": "def",
    "age": "23"
  }
]');

然后值喜欢

select doc from justjson;

doc
[{"age": "22", "name": "abc"}, {"age": "23", "name": "def"}]

现在我想在这个 jsonb 中追加新对象

{"age": "45", "name": "xyz"}

我如何更新这个字段?

我的输出如

doc
    [{"age": "22", "name": "abc"}, {"age": "23", "name": "def"},{"age": "45", "name": "xyz"}]

使用串联运算符 || 将元素附加到数组:

UPDATE justjson
SET doc = doc || '{"age": "45", "name": "xyz"}'::jsonb
WHERE is = 1;