简体   繁体   中英

Query for array values within jsonb column

I have a jsonb column called chores in my work table with data looking something like this:

[{"task": "feed_dog", "value": "Daily"},{"task": "mop_floor", "value": "Weekly"]

There could be zero to dozens of tasks in the chores array for each user.

How can I query by task name? For example, pull all records where at least one task is feed_dog .

SELECT chores->>'task' FROM work returns a bunch of null results, as does SELECT chores->'task' FROM work .

You need to unnest the array:

select w.*
from "work" w
where exists (select *
              from jsonb_array_elements(w.chores) as t(task)
              where t.task ->> 'task" = 'feed_dog');

With Postgres 12 this is a bit easier to write:

select *
from "work" w
where jsonb_path_exists(w.chores, '$[*] ? (@.task == "feed_dog")')

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