Postgresql的jsonb操作--存儲對象/對象數組


1. 建表

create table demo(
    id   serial  NOT NULL PRIMARY KEY,
    name VARCHAR(20),
    info JSONB
);

2.存儲對象操作

2.1添加

insert into demo (name, info)values ('張三1', '{"age":12, "class":"二年級"}');
insert into demo (name, info)values ('張三', '{"age":16, "class":"五年級"}');
insert into demo (name, info)values ('張三3', '{"age":20, "class":"初一"}');

2.2. 查詢

2.2.1 查詢年齡12歲的信息

這里好像是對象中的字符串匹配,如果把數字12變成"12"就會匹配不到

select * from demo where info @> '{"age":12}'::jsonb
2.2.2 查詢年齡大於16歲的信息

這里將jsonb中的屬性轉化為了int

select * from demo where (info->>'age')::int4 > 16

2.3 修改  

jsonb中的屬性修改,某一鍵值對修改,使用jsonb_set函數

update demo as d set 
info = jsonb_set
( 
    (select info from demo where id = d.id)::jsonb,-- target 這是目的json數據,這里使用內部關聯將對應的json查詢出來
    '{class}', -- path 要修改的jsonb中對應的key
    '"語文"'::jsonb, -- new_value 替換的value
    false -- create_missing:: true:- 如果不存在對應的key值,則新增,反之,false - 不做其他操作,這里可有可無
) where id = 1;

 3.存儲對象數組

3.1添加

 

insert into demo (name, info)values ('李四', '[{"age":8, "class":"一年級"},{"age": 10, "class": "三年級"}]');
insert into demo (name, info)values ('李四2', '[{"age":12, "class":"五年級"},{"age":16, "class":"初三"}]');
insert into demo (name, info)values ('李四3', '[{"age":19, "class":"高一"},{"age":8, "class":"一年級"}, {"age":10, "class":"三年級"}]');

 

3.2 修改

3.2.1 追加對象數組
update demo set info = info || '[{"age":9,"class":"二年級"}]'::jsonb where id = 1;

 

3.2.2 修改數組中某一對象屬性
update demo d set info = jsonb_set(
    info,
    array[
        (select ORDINALITY::INT - 1 FROM demo d2,
         jsonb_array_elements(info) WITH ORDINALITY WHERE d.id = d2.id AND value->>'class' = '三年級')::text, -- 確定到准確的對象中
        'class' -- 需要修改的key
    ],
    '"四年級"' -- 替換的value
)where id = 1;

 

3.3 查找

select * from demo where info @> '[{"class": "三年級"}]'; 

 

3.4 遍歷

用到了jsonb_to_recordset函數

SELECT t.* FROM demo, jsonb_to_recordset(info) AS t(age int, class text) WHERE demo.id=7;

 

 

 

 

 

 

 

 
 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM