Union simple arrays in $group stage

Hello everyone,

I’m trying to write an aggregation to return information about my sources and I can’t find a simple way to union values of arrays of the documents I group.

Source docs

{
     "_id" : "123", 
     "C" : "C1", 
     "K" : "K1" ,
.....(much more fields)
     "Fs" : [ 
          "F1","F3" 
    ]
 },
{
     "_id" : "264", 
     "C" : "C1", 
     "K" : "K1" ,
.....(much more fields)
     "Fs" : [ 
          "F2","F3" 
    ]
 }

Wanted Doc

{
   "_id" : { "C" : "C1", "K" : "K1" }
.....(much more fields)
   "Fs":[
         "F1","F2","F3"
   ]
}

I managed to obtain this result using an $unwind before my $group; but my question is:

There’s a simple way to use just one $group step? Something equivalent to a SQL Union.

Thanks

What is the issue with using

How would you do that use case with

To me it looks like SQL UNION is not related at all to this kind of grouping.

I fear that, in production, it will take too long to execute. We’ll find out.

In my head SQL Union was the better example, if you prefer c# it will be
l.SelectMany(x=>x.Fs).Distinct()

Where is the equivalent of having “_id” : { “C” : “C1”, “K” : “K1” } as a group key in the above c# SelectMany? I feel the above do a lot less work that your Wanted Doc.

Optimizing too early is not good because the performance issues might be elsewhere than where we fear they will be. Implements using the simpler code and optimize only if you have issues.