首页 > 解决方案 > Postgres jsonb 嵌套数组追加

问题描述

我有一个带有jsonb列的简单表

CREATE TABLE things (
  id SERIAL PRIMARY KEY,
  data jsonb
);

数据如下:

{
    "id": 1,
        "title": "thing",
        "things": [
            {
                "title": "thing 1",
                "moreThings": [
                    { "title": "more thing 1" }
                ]
            }
        ]
}

那么我如何附加到一个深度嵌套的数组中moreThings呢?

对于单级嵌套数组,我可以这样做并且它有效:

UPDATE posts SET data = jsonb_set(data, '{things}', data->'things' || '{ "text": "thing" }', true);

但同样不适用于深度嵌套的数组:

UPDATE posts SET data = jsonb_set(data, '{things}', data->'things'->'moreThings' || '{ "text": "thing" }', true)

我怎样才能追加到moreThings

标签: postgresqljsonb

解决方案


它工作得很好:

UPDATE things
SET data =
    jsonb_set(data,
              '{things,0,moreThings}',
              data->'things'->0->'moreThings' || '{ "text": "thing" }',
              TRUE
    )
WHERE id = 1;

如果你有一个只包含一个主键和一个jsonb属性的表,并且你经常想jsonb在数据库中操作它,那么你肯定做错了。如果您对数据进行更多规范化,您的生活将会轻松得多。


推荐阅读