MongoDB.live, free & fully virtual. Register Now MongoDB.live, free & fully virtual. Register Now

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

Hi

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


Thank you in advance
Ezequias

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:
$mergeObjects

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

Michael

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.

Thanks,

Justin

2 Likes

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
Michael

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?

Regards
Ezequias Rocha

Hi @Ezequias_Rocha!

The $unionWith stage is available in Compass editions 1.22.0 and up, all of which are in some form of beta.

They are available to download, just keep the beta state in mind!

1 Like