You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PostgreSQL中批量更新JSONB数组内对象的指定key值

PostgreSQL批量修改JSONB数组中所有匹配对象的type字段

需求说明

需要将表中JSONB类型列application_questions(存储对象数组)里,所有type值为multi-select-check的对象,统一修改为type: "multi-select-combo",其余对象保持不变。

示例数据

id (int)application_questions (JSONB)
1[{"id":1,"type":"single-select"},{"id":2,"type":"multi-select-check"}, {"id":3,"type":"single-select"},{"id":4,"type":"multi-select-check"}, {"id":5,"type":"single-select"},{"id":6,"type":"multi-select-check"}]
2[{"id":1,"type":"single-select"},{"id":2,"type":"multi-select-check"}, {"id":3,"type":"single-select"},{"id":4,"type":"multi-select-check"}]
3[{"id":1,"type":"single-select"},{"id":2,"type":"multi-select-check"}, {"id":3,"type":"single-select"},{"id":4,"type":"multi-select-check"}]

解决方案SQL

直接执行以下更新语句,即可批量修改数组中所有符合条件的对象:

-- 替换your_table_name为实际表名
UPDATE your_table_name
SET application_questions = (
  SELECT jsonb_agg(
    CASE 
      WHEN elem->>'type' = 'multi-select-check' 
      THEN elem || '{"type": "multi-select-combo"}'::jsonb
      ELSE elem
    END
  )
  FROM jsonb_array_elements(application_questions) AS elem
)
-- 仅更新包含需要修改元素的行,提升效率
WHERE application_questions @> '[{"type": "multi-select-check"}]'::jsonb;

语句解释

  • jsonb_array_elements(application_questions):将JSONB数组拆分为单个元素的行数据,方便逐个处理
  • CASE判断:对每个元素检查type值,匹配目标值时用||运算符合并新的type字段(覆盖旧值),不匹配则保留原元素
  • jsonb_agg(...):将处理后的所有元素重新聚合为JSONB数组,替换原列值
  • WHERE条件:过滤出确实包含multi-select-check的行,避免对无修改需求的行执行更新,提升性能

验证结果

执行更新后,可通过以下查询确认修改效果:

SELECT id, application_questions
FROM your_table_name;

内容的提问来源于stack exchange,提问作者Daniel Dwyer

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.21 19:33:23