How to query nested array of objects and group & count by one of its properties? Tips?

There are a few things not clear in your requirement.

  1. In the input document you have value “x”, lower case but in the output you have “X”, upper case. It is a typo or something else.
  2. For “Category” and “Class”, upper case C in the input collection you seem to have “category” and “class”, lower case c, should they be the same or you want them to be mapped to lower case.
  3. You seem to treat trait_type:Resource and value:Oil completely differently than the others. You create a root document with name:Old,type:Resource while for the other you create sub-documents with trait_type as the field name. Why the difference? How do you determine which from the attributes array makes the root document name and type?