建表
创建一张包含bson(json的二进制数据类型)数据类型的表
-- data为要存储json数据的字段
create table testjson(id int, data bson);
插入json数据
insert into testjson values(1, '{"name": "GBASE", "address": "天津 南开华苑"}'::json);
查询json数据
select data::json from testjson;
查询json指定字段address
select bson_extract(data, "address")::bson::json from testjson;
当指定字段的值是json对象时,从对象中提取指定key的值
-- other的value是json对象
insert into testjson values(2, '{"name": "gbase", "other": {"address": "天津南开", "number": 123456}}'::json);
-- 从other的value中提取number的值
select bson_extract(data, "other.number")::bson::json from testjson;
当指定字段的值是列表时,提取列表中指定位置的元素
-- other的value是列表,列表中的元素是json
insert into testjson values(2, '{"name": "gbase", "other": [{"address": "天津南开", "number": 123456}, {"address": "天津海泰", "number": 88888}]}'::json);
-- 从other的value中提取第二个元素(序号从0开始)的address
select bson_extract(data, "other.1.address")::bson::json from testjson;