Assuming the following schema in PostgreSQL 9.3:
create table test (data json);
insert into test values ('{
"id" : 1,
"name" : "abc",
"values" : [{"id" : 2, "name" : "cde"}, {"id" : 3, "name" : "def"}]
}'::json);
insert into test values ('{
"id" : 4,
"name" : "efg",
"values" : [{"id" : 5, "name" : "fgh"}, {"id" : 6, "name" : "ghi"}]
}'::json);
What is the best way to query for documents where at least one of the objects in the "values" array satisfy a criteria? The only way I could come up with is this:
select data
from (select
data,
json_array_elements(data->'values')->>'name' as valueName
from test) a
where valueName = 'ghi';
Is there a way to do this without the nested query? In MongoDB I could simply say:
db.test.find({values : {$elemMatch : {name : "ghi"}}});