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

Hello.

I have this type of objects in my collection and I need to be able to group them by attributes. (which is nested array).
The problem is the attributes array when unwinded I loose sight of what are neighbouring attributes. So I atm don’t have a good ideas on how to count totals. Any ideas or suggestions how I should transform collection in the first place.

{
	"id": 3,
	"attributes": [
        {
		"trait_type": "Category",
		"value": "x"
	}, {
		"trait_type": "Resource",
		"value": "Oil"
	}, 
       {
		"trait_type": "Class",
		"value": "High"
	},
        {
		"trait_type": "Class",
		"value": "Mid"
	}
]
}

and I need to be able to get this output from agregation pipeline.

{
    "name": "Oil",
    "type": "Resource",
    "category": [
      {
        "name": "X",
        "occurrence": 100
      }
    ],
    "class": [
      {
        "name": "High",
        "occurrence": 50
      },
      {
        "name": "Mid",
        "occurrence": 50
      }
    ],
    "total": 100
  }
}

I am pretty sure you may apply the same solution as

1 Like

You might be able to do something similar to the other question, but what’s not clear to me is where are the numbers in the final document you want going to come from? What is the total of?

Hey, thanks for reply. The numbers are totals of values present in the collection across the arrays

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?