Watch keynotes and sessions from, our virtual developer conference.

How do I perform an union of two distinct collection in aggregation framework


I would like to know how to perform an union (collection below another collection) in aggregation framework.

Thank you in advance

Hello @Ezequias_Rocha

could you please provide a brief example what you want to archive? There are options to build something like SQL union statement. But generally the ‘need’ of an union, raises a question about your data model.

In case you want to combine multiple documents into a single document you can use:

If you want to combine two or more arrays into one array containing the elements that appear in any input array you can use


1 Like

I actually want to merge two collections (or subsets of collections) in a single document. Maybe I must use the $merge but how to I pass the documents to the aggregation pipeline?

Thank you.

Hi @Ezequias_Rocha,

There’s also the $unionWith aggregation stage currently scheduled for MongoDB version 4.4 that may meet your needs.

As a quick word of caution, version 4.4 hasn’t been finalized yet so there are no guarantees it will make it into the release.




I had a similar situation and this stackoverflow helped

Hello @Ezequias_Rocha

the $unionWith aggregation stage which @Justin mentioned looks very promising and will simplify the code a lot. There is a release candidate 4…4.0.rc0 available you may want to try that out (I will next week).

I once had this issue too, but could fix it by adopting the needs to my data model, that is not always possible. Checking stackoverflow I found this anwers (which comes close to the one @Natac13 already posted.)

Hope that helps

1 Like

Hi @Michael

Could you tell me why this aggregation keywords (stages) doesn’t appears at MongoDB Compass?

How could I apply this aggregation in Compass? Could you tell me how?

Ezequias Rocha