Union between 2 collections into a new one

Hi,

I would like to make the union of all documents of 2 existing collection into a non pre-existing third one. What is the best way to perform this operation?

Hi @Matteo_Tarantino ,
if i understand correctly your question, the better way to do this, i think is to dump and restore all document in the same collection.

so:
image
image



image

i hope is useful,
best regards

1 Like

Very useful, thank you!

1 Like

The mongodump/mongorestore will work but might be extremely slow as all documents from both collections are transferred twice over the wire and are stored locally temporary.

A better approach would be to use $merge. There will be no data transfer over the wire and no data stored locally.

db.people.aggregate( { "$merge" : "people_restaurant" } )
db.restaurant.aggregate( { "$merge" : "people_restaurant" } )
2 Likes

I agree that dump and restore is a VERY inefficient way to do this. Why wouldn’t you just use $unionWith
aggregation stage (and then $out to write the result into a new collection?)

db.coll1.aggregate( [{$unionWith: {coll: "coll2"}}, {$out: "newCollection"}] )

Asya

3 Likes

I proposed 2 $merge because I did not know about $unionWith. Now I know better. Thanks.

1 Like

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