A better way of Grouping an array together into a single document

Hi all,
I’m using MongoDB 5.3.1 Community and NodeJS.

I have data that looks a bit like this:

“Specs”: [{
“Group”: “A”,
“Name”: “ABC” },
{ “Group”: “A”,
“Name”: “123” },
{ “Group”: “B”,
“Name”: “A12” }

Using an aggregation I would like to remodel it to look something like this:

"Specs: [{
“A”: [{
“Name”: “ABC” },
“Name”: “123” }],
“B”: [{
“Name”: “A12” }]

I know I could use $unwind $project and $push to do this. But I’m thinking there must be a better way. The end game is to end up with a single document. I’m wondering is $setWindowFields would be a better option? But I can seem to get it to do what I want it to.


You’re right that going from single document to same single document should not involve any unwinding and grouping, just field transformation.

I can tell you that the transformation will probably involve $map expression and you’ll want to use $setUnion of ”$Specs.Group” expression to “seed” your input.

Let me know if you’d like to see the entire solution or if this was enough to get you started in the right direction.


1 Like

Hi there Asya,

Thanks for the response. I’ve tried my best to work it out based on your advice, but keep running into a brick wall.

Is there any chance of a little more help please?


I found this post by your good self and have managed to work it out from there.

Thanks again.


Hi @Andy_Bryan - I’m glad you were able to solve the problem!


This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.