Postgres GROUP BY on jsonb inner field Postgres GROUP BY on jsonb inner field postgresql postgresql

Postgres GROUP BY on jsonb inner field


You have to use the #>> operator instead of ->> when the right operand is a json path. Try this:

SELECT json_agg(content) as content FROM test GROUP BY content #>> '{a,b}';

Yields:

              content------------------------------------ [{"a": {"c": 1}}] [{"a": {"b": 2}}] [{"a": {"b": 1}}, {"a": {"b": 1}}](3 rows)


I think json_agg() is not the best choice to use it here, since that is concatenating the content values (the whole json data) into an array for a specific group.
It makes more sense to use something like this (and I added 'count(*)', just to have a more common scenario):

SELECT content #>> '{a,b}' as a_b, count(*) as count FROM test GROUP BY content #>> '{a,b}';