更新包含多个对象的 jsonb 列中的特定记录

Update specific record inside jsonb column containing multiple objects

考虑具有此特定记录的 jsonb 类型的名为“DocumentInformation”的列:

[
 {
    "SchoolsCode": 22,
    "SchoolsName": "Home School",
  },
  {
    "SchoolsCode": "101770",
    "SchoolsName": "Blossom Senior High School",
  }
]

这是我尝试使用的 postgresql 查询,用于根据 SchoolName 更新 schoolCode 的值。

Update SchoolRecords set DocumentInformation = jsonb_set(documentInformation, '{schoolCode}', '"00001"') where documentInformation ->> 'SchoolName' = 'Home School'

但是得到失败响应为:

UPDATE 0

Query returned successfully in 401 msec.

你必须找到要修改的数组的索引,然后用jsonb_set修改它:

with my_json as (
select ('{'||index-1||',SchoolsCode}')::text[] as path
from school_records,
jsonb_array_elements(document_information) with ordinality arr(di,index)
 where di->> 'SchoolsName'='Home School'
)
update school_records set document_information = jsonb_set(document_information,my_json.path,'"000001"')
from my_json;

Result here