简体   繁体   中英

In PostgreSQL, what's the best way to select an object from a JSONB array?

Right now, I have an an array that I'm able to select off a table.

[{"_id": 1, "count: 3},{"_id": 2, "count: 14},{"_id": 3, "count: 5}]

From this, I only need the count for a particular _id. For example, I need the count for

_id: 3

I've read the documentation but I haven't been able to figure out the correct way to get the object.

WITH test_array(data) AS ( VALUES
  ('[
     {"_id": 1, "count": 3},
     {"_id": 2, "count": 14},
     {"_id": 3, "count": 5}
     ]'::JSONB)
)
SELECT val->>'count' AS result
FROM
  test_array ta,
  jsonb_array_elements(ta.data) val
WHERE val @> '{"_id":3}'::JSONB;

Result:

 result 
--------
 5
(1 row)

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