简体   繁体   中英

Query nested jsonb Postgres column

I have a metadata column of type jsonb .

I know how to check whether it contains a specific key:

obj = Model.create
obj.metadata = {"foo"=>"1", "bar"=>{"baz"=>{"qux"=>2}}}

Model.where("(metadata->'bar') IS NOT NULL") # returns obj

I wonder, how would I check if there is baz key in obj.metadata['bar'] and, if I had, for deeper nested keys?

Ok, just found a way:

Model.where("(metadata -> 'bar' ->> 'baz') IS NOT NULL")

if metadata has more nested json:

obj.metadata = {"foo"=>"1", "bar"=>{"baz"=>{"qux"=>2}}}

and I would want to see, if there's metadata['bar']['baz']['qux'] :

Model.where("(metadata -> 'bar' -> 'baz' ->> 'qux') IS NOT NULL")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM