Reputation: 57
I have a table in PostgreSQL
CREATE TABLE IF NOT EXISTS account_details
(
account_id integer,
condition json
);
And the data's present inside this table are
account_id | condition |
---|---|
1 | [{"action":"read","subject":"rootcompany","conditions":{"rootcompanyid":{"$in":[35,20,5,6]}}}] |
2 | [{"action":"read","subject":"rootcompany","conditions":{"rootcompanyid":{"$in":[1,4,2,3,6]}}}] |
3 | [{"action":"read","subject":"rootcompany","conditions":{"rootcompanyid":{"$in":[5]}}}] |
I need to fetch the details of all account having rootcompanyid in (5). IF part of any **rootcompanyid's ** are present in any of the account details should display the result. So output should contain account_id --> 1 and 3 rows
The below query is fetching only the last row (account_id = 3) not the first row
SELECT *
FROM account_details
WHERE ((condition->0->>'conditions')::json->>'rootcompanyid')::json->>'$in' = '[5]';
Expected Output : IF part of any **rootcompanyid's ** are present in any of the account details should display the result.
account_id | condition |
---|---|
1 | [{"action":"read","subject":"rootcompany","conditions":{"rootcompanyid":{"$in":[35,20,5,6]}}}] |
3 | [{"action":"read","subject":"rootcompany","conditions":{"rootcompanyid":{"$in":[5]}}}] |
Upvotes: 2
Views: 197
Reputation: 246533
That's easily done with the JSON containment operator:
WHERE condition::jsonb @> '[ { "conditions": { "rootcompanyid": { "$in": [5] } } } ]'
If you want to search for more than a single array element, either use two of the above conditions with OR
or use a JSONPATH query:
WHERE jsonb_path_exists(
condition::jsonb,
'$[*].conditions.rootcompanyid.\$in[*] ? (@ == 5 || @ == 6)'
)
Upvotes: 4